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:

  1. Object.keys(details) gets all property names from the details object
  2. map() transforms each key into a new object structure
  3. The spread operator ...details[key] copies existing properties
  4. The conditional operator checks if the student name exists in join_values
  5. 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.

Updated on: 2026-03-15T23:18:59+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements