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
Appending a key value pair to an array of dictionary based on a condition in JavaScript?
In JavaScript, you can append key-value pairs to objects within an array or dictionary based on conditions using Object.assign() or the spread operator. This is useful when you need to add properties conditionally.
Problem Statement
Given a dictionary of student objects, we want to add a lastName property based on whether the student's name appears in a specific array.
Using Object.assign() with Conditional Logic
The following example demonstrates how to append a lastName property to each student object based on a condition:
const details = {
john: {'studentName': 'John'},
david: {'studentName': 'David'},
mike: {'studentName': 'Mike'},
bob: {'studentName': 'Bob'},
carol: {'studentName': 'Carol'}
};
const join_values = ['David', 'Carol'];
const output = Object.assign(
{},
...Object
.keys(details)
.map(key => ({
[key]: {
...details[key],
lastName: join_values.includes(details[key].studentName)
? 'Miller'
: 'Smith'
}
}))
);
console.log(output);
{
john: { studentName: 'John', lastName: 'Smith' },
david: { studentName: 'David', lastName: 'Miller' },
mike: { studentName: 'Mike', lastName: 'Smith' },
bob: { studentName: 'Bob', lastName: 'Smith' },
carol: { studentName: 'Carol', lastName: 'Miller' }
}
How It Works
The code performs the following steps:
-
Object.keys(details)gets all property names from the details object -
map()transforms each key into a new object structure - The spread operator
...details[key]copies existing properties - The conditional operator checks if the student name exists in
join_values -
Object.assign()merges all mapped objects into a single result
Alternative Approach Using forEach
For a more straightforward approach, you can modify the original object directly:
const details = {
john: {'studentName': 'John'},
david: {'studentName': 'David'},
mike: {'studentName': 'Mike'}
};
const join_values = ['David'];
Object.keys(details).forEach(key => {
details[key].lastName = join_values.includes(details[key].studentName)
? 'Miller'
: 'Smith';
});
console.log(details);
{
john: { studentName: 'John', lastName: 'Smith' },
david: { studentName: 'David', lastName: 'Miller' },
mike: { studentName: 'Mike', lastName: 'Smith' }
}
Comparison
| Method | Creates New Object | Modifies Original | Performance |
|---|---|---|---|
Object.assign() |
Yes | No | Slower |
forEach() |
No | Yes | Faster |
Conclusion
Use Object.assign() when you need to preserve the original object, or forEach() for direct modification. Both approaches allow conditional key-value pair addition based on specific criteria.
