1

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
}

1 Answer 1

1

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]}
Sign up to request clarification or add additional context in comments.

1 Comment

essentially it's refactored method ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.