如何在 JavaScript 中为计算属性分配值?


以下是我们的对象 -

const customerDetails=[
   {customerFirstName: "David"},
   {customerLastName: "Miller"},
   {customerCountryName: "US"},
   {customerAge: "29"},
   {isMarried: false},
   {customerCollegeName: null}
];

让我们使用 slice() 和 map() 为计算属性分配值。

示例

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);

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

node fileName.js.

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

输出

这将产生以下输出 -

PS C:\Users\Amit\JavaScript-code> node demo135.js
[
   { propertyKey: 'customerCountryName', propertyValue: 'US' },
   { propertyKey: 'customerAge', propertyValue: '29' },
   { propertyKey: 'customerCollegeName', propertyValue: null }
]

更新于: 11-Sep-2020

151 次观看

开启您的 职业生涯

完成课程获得认证

开始
广告
© . All rights reserved.