Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Appending a key value pair to an array of dictionary based on a condition in JavaScript?
For this, use Object.assign(). Following is the code −
Example
const details =
{john:{'studentName':'John'},david:{'studentName':'David'},mike:{'studen
tName':'Mike'},bob:{'studentName':'Bob'},carol:{'studentName':'Carol'}},
join_values = ['David', 'Carol'],
output = Object.assign(
{},
...Object
.keys(details)
.map(key =>
({[key]: {
...details[key],
lastName: join_values.includes(details[key].studentName) ?
'Miller' : 'Smith'
}})))
console.log(output)
To run the above program, you need to use the following command −
node fileName.js.
Output
Here, my file name is demo157.js. This will produce the following output −
PS C:\Users\Amit\JavaScript-code> node demo157.js
{
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' }
}Advertisements