0

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"});
Bigjo
  • 613
  • 2
  • 10
  • 32
  • 1
    *"I have a JSON object"* No, [you don't](http://stackoverflow.com/a/2904181/157247). You have a JavaScript object. You don't have a JSON array, either. JSON is a *textual notation* for data exchange. If you're dealing with JavaScript source code, and not dealing with a *string*, you're not dealing with JSON. – T.J. Crowder May 08 '17 at 18:21
  • *"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:"* What *do* you want to have happen? – T.J. Crowder May 08 '17 at 18:22
  • I don't want to be able to push another object in my retrieveSections array that already exists. So in other words I want to test if the object {key:5, label:"Joelle Six"} already exists in the retrievesections before making the push. – Bigjo May 08 '17 at 18:27
  • Okay, good -- that's what my answer shows you how to do. – T.J. Crowder May 08 '17 at 21:13

1 Answers1

1

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.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875