首页 > 解决方案 > 将值和键从一个数组复制到另一个数组

问题描述

我有看起来像这样从 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); ,但这只会将值返回到新数组中。如何创建具有不同键但值来自原始数组的新数组?

标签: javascript

解决方案


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

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

推荐阅读