如何在對 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' ] ]
廣告