I'm working with an api in a mern app, on the backend I would like to destructor the array of objects, run a function on an item each each of the arrays and return a new array of objects or add the new value to the array. Here is my controller
const getObjects = async (req, res) => {
const { bucketKey } = req.params
const bucket = await new ForgeSDK.ObjectsApi().getObjects(
bucketKey,
req.params.objectName,
req.oauth_client,
req.oauth_token
)
const bucketObjects = bucket.body.items
// const encodedUrn = urnify(objectKey)
res.status(StatusCodes.OK).json({
bucketObjects,
totalObjects: bucketObjects.length,
numOfPages: 1,
})
}
So each item in the array of bucketObjects has an objectKey, I would like to take the objectKey convert it to a Base64-encoded string and create a new array of objects
Here is the response I am returning in postman
"bucketObjects": [
{
"bucketKey": "dashboard",
"objectKey": "BRISMETRO-BRM-ADLSTSO00-3DM-000020.ifc",
"objectId": "urn:adsk.objects:os.object:dashboard/BRISMETRO-BRM-ADLSTSO00-3DM-000020.ifc",
"sha1": "4ed04b922c8863ac8323226da2a5f974730d13f0",
"size": 937888,
"location": "https://developer.api.autodesk.com/oss/v2/buckets/dashboard/objects/BRISMETRO-BRM-ADLSTSO00-3DM-000020.ifc"
},
CodePudding user response:
You can simply use map function to return a new array.
const newArray = bucketObjects.map((object) => {
return {
...object,
objectKey: conversionToBase64(object.objectKey)
}
})
CodePudding user response:
Transform each element of your array with a simple forEach
iterator before sending the response.
const getObjects = async (req, res) => {
...
const bucketObjects = bucket.body.items;
bucketObjects.forEach(obj => obj.key = new Buffer(obj.objectKey).toString('base64'));
res.status(StatusCodes.OK).json({
bucketObjects,
...