将数组添加到JSON对象(如果不存在)

mav*_*raj 0 javascript json

我有这个JSON对象:

var collection = {
    "123":{
      "name": "Some Name",
      "someArray": [
          "value 0",
          "value 1"
       ]
     },
    "124":{
      "name": "Some Name"
     }, 
Run Code Online (Sandbox Code Playgroud)

我有一个更新和返回集合的方法,例如:

function updateCollection(id, property, value){
return collection;
}
Run Code Online (Sandbox Code Playgroud)

假设方法调用是这样的:

updateCollection(124, someArray, "value 3");
Run Code Online (Sandbox Code Playgroud)

我应该如何更新?我已经写的是:

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

调用方法后的预期输出updateCollection(124, someArray, "value 3");应为:

"124":{ "name": "Some Name", "someArray": [ "value 3", ] }
Run Code Online (Sandbox Code Playgroud)

adi*_*iga 5

用just创建一个新数组value并将其分配给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;
  }
Run Code Online (Sandbox Code Playgroud)