Bigjo
Bigjo

Reputation: 633

Push distinct objects in JSON array in javascript

I have a JSON object:

var retrieveSections=[{key:1, label:"James Smith"} ];

I want to push some other objects in it like this one:

retrieveSections.push({key:5, label:"Joelle Six"});

But when I tried to add another object with the same key and label, I don't want it to be added to my JSON object. So I don't want to be able to push this object again:

retrieveSections.push({key:5, label:"Joelle Six"});

Upvotes: 0

Views: 955

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074505

I don't want it to be added to my JSON object. So I don't want to be able to push this object again

You'll have to handle that intentionally, by searching first to see if an entry with that key already exists.

if (!retrieveSections.some(function(entry) { return entry.key === newEntry.key;})) {
    retrieveSections.push(newEntry);
}

Or in modern JavaScript (ES2015+):

if (!retrieveSections.some(entry => entry.key === newEntry.key)) {
    retrieveSections.push(newEntry);
}

But the fact you're using unique keys suggests you may want an object or Map rather than an array, at least while you're building it, to make the checks for pre-existing keys faster. Then when you're done you can produce an array from the result, if it needs to be an array.

Upvotes: 1

Related Questions