Add object to array in JavaScript if name does not already exist?

To add objects to an array only if they don't already exist, you can use push() combined with find() to check for duplicates. This prevents adding duplicate entries based on specific criteria.

Basic Example

Here's how to add objects to an array if the name property doesn't already exist:

var details = [{name: "John"}, {name: "David"}];
var addObject = ["Mike", "Sam", "John"]; // "John" already exists

addObject.forEach(obj1 => {
    if (!details.find(obj2 => obj2.name === obj1)) {
        details.push({name: obj1});
    }
});

console.log(details);
[
  { name: 'John' },
  { name: 'David' },
  { name: 'Mike' },
  { name: 'Sam' }
]

Adding Complete Objects

You can also add complete objects while checking for duplicates:

var users = [{name: "Alice", age: 25}, {name: "Bob", age: 30}];
var newUsers = [
    {name: "Charlie", age: 35},
    {name: "Alice", age: 26},  // Different age, same name
    {name: "Diana", age: 28}
];

newUsers.forEach(newUser => {
    if (!users.find(user => user.name === newUser.name)) {
        users.push(newUser);
    }
});

console.log(users);
[
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 30 },
  { name: 'Charlie', age: 35 },
  { name: 'Diana', age: 28 }
]

Using Filter and Concat

An alternative approach using filter() and concat():

var products = [{name: "Laptop"}, {name: "Phone"}];
var newProducts = ["Tablet", "Laptop", "Camera"];

var uniqueProducts = newProducts
    .filter(product => !products.find(p => p.name === product))
    .map(product => ({name: product}));

var result = products.concat(uniqueProducts);
console.log(result);
[
  { name: 'Laptop' },
  { name: 'Phone' },
  { name: 'Tablet' },
  { name: 'Camera' }
]

Key Points

  • find() returns the first matching element or undefined
  • Use === for exact property comparison
  • forEach() modifies the original array
  • filter().concat() creates a new array without modifying the original

Conclusion

Use find() to check for existing objects before adding new ones. This approach prevents duplicates and maintains data integrity in your arrays.

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

994 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements