Reputation: 2599
I have data that looks like this returning from an api
var data = {
"entities": [
{
"documentbody": Base64String,
"filename": "http-status-code-cheat-sheet1.png",
"filesize": 204326,
"mimetype": "image/png",
},
{
"documentbody": null,
"filename": "http-status-code-cheat-sheet2221.png",
"filesize": 204326,
"mimetype": "image/png",
}
]
}
I would like to create a new array that looks like this
var images = [
{ imgsrc:(documentBodyValue),imgDesc:(fileNameValue)},
{imgsrc:(documentBodyValue),imgDesc:(fileNameValue)}
]
I have tried using the map function let result = data.entities.map(a => a.filename);
but this only returns the values into a new array. How can i create a new array with different keys but values from the original array?
Upvotes: 0
Views: 55
Reputation: 196026
Just return a new object from the map for each item.
let result = data.entities.map(a => ({imgsrc: a.documentbody, imgDesc: a.filename}));
Upvotes: 4
Reputation: 11584
Your attempt is almost correct. You can use {key: value, ...}
syntax to map to an obj instead of values. E.g.:
var data = {
"entities": [
{
"documentbody": 'Base64String',
"filename": "http-status-code-cheat-sheet1.png",
"filesize": 204326,
"mimetype": "image/png",
},
{
"documentbody": null,
"filename": "http-status-code-cheat-sheet2221.png",
"filesize": 204326,
"mimetype": "image/png",
}
]
};
let result = data.entities.map(a => ({imgsrc: a.documentbody, imgDesc: a.filename}));
console.log(result);
Upvotes: 3
Reputation: 1648
var images = []
data.entities.forEach(entry => {
images.push({imgsrc: entry.documentbody, imgDesc: entry.filename})
})
Upvotes: 2