简体   繁体   中英

Checking existence of object in Array in Javascript based on a particular value

I have an array of objects, and want to add a new object only if that object doesn't already exist in the array. The objects in the array have 2 properties, name and imageURL and 2 objects are same only if their name is same, and thus I wish to compare only the name to check whether the object exists or not How to implement this as a condition??

You can use Array.find

let newObj={ name:'X',imageURL:'..../'}
if(!array.find(x=> x.name == newObj.name))
   array.push(newObj)

Since you've not mentioned the variables used. I'll assume 'arr' as the array and 'person' as the new object to be checked.

const arr = [{name: 'John', imageURL:'abc.com'},{name: 'Mike', imageURL:'xyz.com'}];
const person = {name: 'Jake', imageURL: 'hey.com'};
if (!arr.find(
      element => 
      element.name == person.name)
    ) {
       arr.push(person);
    };

If the names are not same, the person object won't be pushed into the array.

You need to check it using find or similar functions like this:



  
  
  
const arr = [{ name: 1 }, { name: 2 }];

function append(arr, newEl) {
  if (!arr.find(el => el.name == newEl.name)) {
    arr.push(newEl);
  }
}

append(arr, { name: 2 }); // won't be added
console.log(arr);

append(arr, { name: 3 }); // will be added
console.log(arr);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM