0

Let's say I have a JSON list like this:

var obj = {"1": "somevalue", "2": "someothervalue"};

How can I add {"3": "somevalue"} to the object dynamically? i.e. without knowing that two keys already that exist.

I'm looking for some JavaScript that looks at the JSON list, then adds a key to the end without accidentally overwriting an existing key.

I understand there is a similar question here: Checking if a key exists in a JavaScript object? but I would like to know how to dynamically generate the next number key e.g. "3" in the example above.

SparrwHawk
  • 13,581
  • 22
  • 61
  • 91
  • Also important to note there's no such thing as adding a key to the "end". Objects' keys are unordered – m0meni Jul 28 '17 at 18:39
  • 1
    Possible duplicate of [Checking if a key exists in a JavaScript object?](https://stackoverflow.com/questions/1098040/checking-if-a-key-exists-in-a-javascript-object) – Chris Cousins Jul 28 '17 at 18:40
  • If the title was true, you'd have a lot harder time, as you'd have to do either string processing or `JSON.parse()` before checking for the existence of the key. That may look like valid JSON, but that is a JavaScript object literal, and so it is not actually serialized even though it is serialized in the source code. – Patrick Roberts Jul 28 '17 at 19:07
  • 1
    Use an array instead of an object, and use the built-in push method. Arrays *are* ordered, and have indices. – James Jul 28 '17 at 19:42

4 Answers4

4

you can use in to check if key exists in object.

if (!(key in obj))
   obj[key] = 'somevalue'
Dij
  • 9,761
  • 4
  • 18
  • 35
0

If you fancy libraries that help you with this, you can use assign from lodash:

var obj = {"1": "somevalue", "2": "someothervalue"};
var obj2 = {"3": "somevalue"};

_.assign(obj, obj2); // Was called _.extend in older versions
Vlatko Vlahek
  • 1,839
  • 15
  • 20
-1

Simply

 if(typeof obj[key] !== 'undefined') {
   obj[key] = value
 }

So in your script it would be better to have it wrapped in a function such like

function appendObj(obj, key, value) {
  if (typeof obj !== 'undefined') { // lets make sure there is an obj first
   if(typeof key!=='undefined' && key && typeof obj[key] !== 'undefined') {
     obj[key] = value;
   }
   else {
    obj.push(value);
   }
  }
}

then whenever you need to add a K/V to any object,

var myNewObj = {"1": "somevalue", "2": "someothervalue"};
appendObj(myNewObj, '4', 'new value') 
serdar.sanri
  • 2,217
  • 1
  • 17
  • 21
  • Can you please explain your condition checking? – Akash KC Jul 28 '17 at 18:39
  • 1
    I'd probably go for something more like `if(!(key in obj))` for the conditional – Gray Jul 28 '17 at 18:40
  • @RyanSpeets `in` isn't reliable. Rather `Object.prototype.hasOwnProperty()` would be best here. – m0meni Jul 28 '17 at 18:43
  • @AR7 I wouldn't say that `in` isn't reliable, the difference between it and `Object.prototype.hasOwnProperty()` is that it also returns `true` for `prototype` properties – Patrick Barr Jul 28 '17 at 18:54
  • @AkashKC because OP asks not to override data if same key exists in object already. – serdar.sanri Jul 28 '17 at 18:55
  • Thanks for your answer, but can you expand on it a bit? I'm a JS newbie and struggling to connect the dots. The following just gets me a "key is not defined" error `var obj = {"1": "somevalue", "2": "somevalue"}; if(typeof obj[key] !== 'undefined') { obj[key] = 'something' }` – SparrwHawk Jul 28 '17 at 18:57
  • `key` in that case is is the index you will be passing, see my update. – serdar.sanri Jul 28 '17 at 18:59
  • But that would not be dynamically generating a key? My point is that I'm not sure what it needs to be, and it would depend on the last key. So if there are 2 keys, literally `"1": "somevalue", "2", "someothervalue"` then I need to dynamically set the 3rd key to be "3" – SparrwHawk Jul 28 '17 at 19:01
  • 1
    Yes and no. If you just want to append a value, you don't need to pass a key nor you need to check it's existence because new item you push will get next available key. but if you want to pass a key and value and want to check to avoid overriding then you need to check existence first then append if it doesn't. makes sense? – serdar.sanri Jul 28 '17 at 19:03
  • Oh ok! I didn't realise it will generate a the next available key automatically. Thanks – SparrwHawk Jul 28 '17 at 19:06
  • I want to define my object with `{ 1: undefined, 2: undefined }` and _not_ override them, thank you very much :| – Patrick Roberts Jul 28 '17 at 19:08
-3

check and see if the property exists

if(! obj[key]) { 
  obj[key] = value;
}
Parker Dell
  • 472
  • 4
  • 11