简体   繁体   中英

Adding an array to a JSON object if it doesn't exist

I have this JSON object:

var collection = {
    "123":{
      "name": "Some Name",
      "someArray": [
          "value 0",
          "value 1"
       ]
     },
    "124":{
      "name": "Some Name"
     }, 

I have a method that updates and returns the collection like:

function updateCollection(id, property, value){
return collection;
}

Suppose the method call is like this:

updateCollection(124, someArray, "value 3");

How should I update? What I already wrote is:

function updateCollection(id, property, value){
  if(collection[id].hasOwnProperty(property)){
    collection[id][property].push(value);
  }
  else{
   //need help here 
  }
  return collection;
}

Expected Output after calling method updateCollection(124, someArray, "value 3"); should be:

"124":{ "name": "Some Name", "someArray": [ "value 3", ] }

Create a new array with just value and assign it to collection[id][property] :

function updateCollection(id, property, value) {
  collection[id] = collection[id] || {}; // if "id" doesn't exist in collection
   if (collection[id].hasOwnProperty(property) {
      collection[id][property].push(value);
    } else {
      collection[id][property] = [value]
    }
    return collection;
  }

I would go a step ahead and insert a new object for any id which does not exist and create a new array for property , if necessary.

function updateCollection(id, property, value) {
    collection[id] = collection[id] || {};
    collection[id][property] = collection[id][property] || [];
    collection[id][property].push(value);
    return collection;
}

Here your code.

 var collection = { "123":{ "name": "Some Name", "someArray": [ "value 0", "value 1" ] }, "124":{ "name": "Some Name" } }; function updateCollection(id, property, value){ var _coll = collection.hasOwnProperty(id) ? collection[id] : {}; _coll[property] = value; collection[id] = _coll; return collection; } console.log(updateCollection(124, "somearray", ['1','2']));

I have updated you code and it should work better for cases with not existed array or values

var collection = {
    "123":{
      "name": "Some Name",
      "someArray": [
          "value 0",
          "value 1"
       ]
     },
    "124":{
      "name": "Some Name"
     }};
function updateCollection(id, property, value) {
  if (collection[id] && collection[id][property]) {
      collection[id][property].push(value);
    }
    else
    {
    collection[id] = {};
      collection[id][property] = [value]
    }
  return collection;  
  }



  updateCollection(124, "someArray", "value 3");
  updateCollection(125, "someArray", "value 3");
  console.log(collection);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM