Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Javascript

กำหนดค่าให้กับคุณสมบัติที่คำนวณใน 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 }
]