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

Updated on: 12-Sep-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements