Dưới đây là đối tượng của chúng ta:
const customerDetails = [
{customerFirstName: "David"},
{customerLastName: "Miller"},
{customerCountryName: "US"},
{customerAge: "29"},
{isMarried: false},
{customerCollegeName: null}
];
Hãy gán giá trị cho thuộc tính tính toán sử dụng slice() cùng với map().
Ví dụ
const customerDetails = [
{customerFirstName: "David"},
{customerLastName: "Miller"},
{customerCountryName: "US"},
{customerAge: "29"},
{isMarried: false},
{customerCollegeName: null}
];
const newCustomerDetails = customerDetails.slice(2,4).concat(customerDetails[5]).map(obj => ({
propertyKey: Object.keys(obj)[0],
propertyValue: Object.values(obj)[0]
}));
console.log(newCustomerDetails);
Để 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à demo135.js.
Kết quả
Chương trình sẽ cho ra kết quả sau:
PS C:\Users\Amit\JavaScript-code> node demo135.js
[
{ propertyKey: 'customerCountryName', propertyValue: 'US' },
{ propertyKey: 'customerAge', propertyValue: '29' },
{ propertyKey: 'customerCollegeName', propertyValue: null }
]