如何在映射和检查条件后将新对象添加到 JavaScript 数组中?
javascriptweb developmentobject oriented programming更新于 2025/11/18 3:56:17
为此,您可以将 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' ]
]
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

