繁体   English   中英

将值和键从一个数组复制到另一个数组

[英]Copy values and keys from one array into another

我有从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)}
]

我已经尝试过使用map函数let result = data.entities.map(a => a.filename); 但这只会将值返回到新数组中。 如何创建一个具有不同键但原始数组值不同的新数组?

只需从地图中为每个项目返回一个新对象即可。

let result = data.entities.map(a => ({imgsrc: a.documentbody, imgDesc: a.filename})); 

您的尝试几乎是正确的。 您可以使用{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); 

var images = []
data.entities.forEach(entry => {
    images.push({imgsrc: entry.documentbody, imgDesc: entry.filename})
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM