Javascript循环遍历对象数组并获取两个值并插入到新的对象数组中

标签 javascript arrays object ecmascript-6

我有一个如下所示的对象数组:

rows [
{ id: 3,
 title: "sometitle", 
 catid: 55, 
 img: "file" },
{ id: 4,
 title: "sometitle", 
 catid: 55, 
 img: "file" },
{ id: 5,
 title: "sometitle", 
 catid: 55, 
 img: "file" },
]

我现在想做的是循环遍历对象数组,并从每个对象中获取两个值(id 和 img)并将其插入到新的对象数组中,这样它最终看起来像这样:

newArr [
{ id: 3,
 img: "file" },
{ id: 4,
 img: "file" },
{ id: 5,
 img: "file" },
]

最佳答案

您可以使用map轻松完成此操作。

var rows = [
{ id: 3,
 title: "sometitle", 
 catid: 55, 
 img: "file" },
{ id: 4,
 title: "sometitle", 
 catid: 55, 
 img: "file" },
{ id: 5,
 title: "sometitle", 
 catid: 55, 
 img: "file" },
];

var newArr = rows.map(function(elem) {
    return {
        id: elem.id,
        img: elem.img
    };
});

console.log('newArr', newArr);

关于Javascript循环遍历对象数组并获取两个值并插入到新的对象数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48666927/

相关文章:

java - map 中的 Ljava.lang.String

java - 从 JTable 中检索对象

java - 从Android SIP类调用SipProfile.Builder时出现未处理的异常

javascript - 如何将点击事件绑定(bind)到动态创建的 TD?

arrays - JSON 与数组中的字典

c++ - 无法在类中使用以数组作为参数的函数模板

python - 具有 namedtuple 的多处理对象 - pickle 错误

javascript - 如何在 emberjs 中获取 afterRender 的 css 宽度

javascript - 错误 : Rule can only have one resource source (provided resource and test + include + exclude)

javascript - 回调有什么意义