如何在对 JavaScript 数组使用 map 和检查条件后,向其中添加新对象?


对此,你可以将 filter() 与 map() 结合使用。

示例

const details =[
   { customerName: 'John', customerCountryName: 'UK', isMarried :true },
   { customerName: 'David', customerCountryName: 'AUS', isMarried :false },
   { customerName: 'Mike', customerCountryName: 'US', isMarried :false }
]
let tempObject = details.filter(obj=> obj.isMarried == true);
tempObject["customerNameWithIsMarriedFalse"] = details.filter(obj =>
obj.isMarried== false).map(obj => obj.customerName);
console.log(tempObject);

要运行上述程序,你需要使用以下命令 -

node fileName.js.

这里,我的文件名是 demo176.js。

输出

这将生成以下输出 -

PS C:\Users\Amit\javascript-code> node demo176.js
[
   { customerName: 'John', customerCountryName: 'UK', isMarried: true }, customerNameWithIsMarriedFalse: [ 'David', 'Mike' ]
]

更新于: 12-09-2020

363 浏览

启动您的 职业生涯

完成课程即可获得认证

开始
广告
© . All rights reserved.