在 JavaScript 中为计算属性赋值?

javascriptweb developmentobject oriented programming更新于 2025/11/15 21:32:17

以下是我们的对象 −

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 }
]

相关文章


有用资源