Để làm điều này, bạn có thể sử dụng filter() cùng với map().
Ví dụ
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);
Để chạy chương trình trên, bạn cần sử dụng lệnh sau:
node fileName.js
Tên tệp của tôi là demo176.js.
Kết quả
Chương trình sẽ cho ra kết quả sau:
PS C:\Users\Amit\javascript-code> node demo176.js
[ { customerName: 'John', customerCountryName: 'UK', isMarried: true }, customerNameWithIsMarriedFalse: [ 'David', 'Mike' ] ]