RaceBase
RaceBase

Reputation: 18848

Adding property to JSON object in Javascript

I am using xml2js to convert xml to js object and add new nodes to the content

Ex1:
<abc>
   <my-node>123</my-node>
   <my-node>456</my-node>
</abc>


Ex2:
<abc>
   <my-node>123</my-node>
</abc>

In the Ex1, the my-node property will be an array whereas in the Ex2, it will be non-array item.

How to add extra my-node to the same. I can do in below format but looking for better solution?

if(typeof abc.my-node == Array){
   abc.my-node.push(xxx);
} else {
   //create empty array
   //add existing element
   //add xxx
   //set the array to json object
}

Upvotes: 1

Views: 921

Answers (1)

Martin Honnen
Martin Honnen

Reputation: 167706

If you use

function addProp(obj, propName, value) {
  if (propName in obj) {
    if (obj[propName] instanceof Array) {
      obj[propName].push(value);
    }
    else if (typeof obj[propName] !== 'object') {
      obj[propName] = [obj[propName], value];
    }
  }
  else {
    obj[propName] = value;
  }
}

var abc = {};
console.log(JSON.stringify(abc));
addProp(abc, 'my-node', 123);
console.log(JSON.stringify(abc));
addProp(abc, 'my-node', 456);
console.log(JSON.stringify(abc));
addProp(abc, 'my-node', 789);
console.log(JSON.stringify(abc));

then the result is

{}
{"my-node":123}
{"my-node":[123,456]}
{"my-node":[123,456,789]}

Upvotes: 1

Related Questions