我有从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",
}
]
}
我想创建一个看起来像这样的新数组
var images = [
{ imgsrc:(documentBodyValue),imgDesc:(fileNameValue)},
{imgsrc:(documentBodyValue),imgDesc:(fileNameValue)}
]
我尝试使用地图功能let result = data.entities.map(a => a.filename);
但这只会将值返回到新数组中。如何创建一个具有不同键但原始数组中的值不同的新数组?
答案 0 :(得分:4)
只需从地图中为每个项目返回一个新对象即可。
let result = data.entities.map(a => ({imgsrc: a.documentbody, imgDesc: a.filename}));
答案 1 :(得分:3)
您的尝试几乎是正确的。您可以使用{key: value, ...}
语法映射到obj而不是值。例如:
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);
答案 2 :(得分:2)
var images = []
data.entities.forEach(entry => {
images.push({imgsrc: entry.documentbody, imgDesc: entry.filename})
})