0

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??

    3 Answers 3

    1

    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.

      1

      You can use Array.find

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

        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);

          Start asking to get answers

          Find the answer to your question by asking.

          Ask question

          Explore related questions

          See similar questions with these tags.