I have a function that takes a JSON object and either creates a new array with an initial element, or adds an element to that array if it already exists:
function pushOrCreate(jsonObj,arrayName,newElement){
if(jsonObj.hasOwnProperty(arrayName)){
jsonObj[arrayName].push(newElement);
}
else{
jsonObj[arrayName]=[newElement];
}
}
Here's a test of this function:
var taskAttributesText='{'+
'"abc":"123",'+
'"xyz":"hello"'+
'}';
var taskAttributes=JSON.parse(taskAttributesText);
pushOrCreate(taskAttributes,"workers","xx8238429");
pushOrCreate(taskAttributes,"workers","aa238232");
console.log(JSON.stringify(taskAttributes));
The function is working correctly, but I'm thinking there must be a simpler way to accomplish this push-or-create operation--it seems like the kind of thing that there's a one-line solution for in Javascript. Is there an easier way to do this?
hasOwnPropertyto justif (jsonObj[arrayName])taskAttributeslike that.var taskAttributes = {abc: 123, xyz: "hello"}. done.