Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Assigning values to a computed property in JavaScript?
In JavaScript, computed properties allow you to create object properties with dynamic names. This article shows how to extract data from an array of objects and assign values to computed properties using array methods.
Sample Data
Let's start with an array of customer details objects:
const customerDetails = [
{customerFirstName: "David"},
{customerLastName: "Miller"},
{customerCountryName: "US"},
{customerAge: "29"},
{isMarried: false},
{customerCollegeName: null}
];
console.log("Original data:", customerDetails);
Original data: [
{ customerFirstName: 'David' },
{ customerLastName: 'Miller' },
{ customerCountryName: 'US' },
{ customerAge: '29' },
{ isMarried: false },
{ customerCollegeName: null }
]
Using slice() and map() for Computed Properties
We can extract specific elements and transform them into objects with computed property names:
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);
[
{ propertyKey: 'customerCountryName', propertyValue: 'US' },
{ propertyKey: 'customerAge', propertyValue: '29' },
{ propertyKey: 'customerCollegeName', propertyValue: null }
]
How It Works
The code performs these steps:
-
slice(2, 4)- Extracts elements at indices 2 and 3 -
concat(customerDetails[5])- Adds the element at index 5 -
map()- Transforms each object into a new structure -
Object.keys(obj)[0]- Gets the first property name -
Object.values(obj)[0]- Gets the first property value
Alternative Approach with Computed Property Names
You can also create objects with truly computed property names:
const customerDetails = [
{customerFirstName: "David"},
{customerLastName: "Miller"},
{customerCountryName: "US"}
];
const result = customerDetails.map(obj => {
const key = Object.keys(obj)[0];
const value = Object.values(obj)[0];
return {
[`computed_${key}`]: value
};
});
console.log(result);
[
{ computed_customerFirstName: 'David' },
{ computed_customerLastName: 'Miller' },
{ computed_customerCountryName: 'US' }
]
Conclusion
Computed properties in JavaScript provide flexibility for dynamic object creation. Use Object.keys() and Object.values() with array methods like map() to transform data structures effectively.
Advertisements
