javascript - 如果 JSON 对象不存在,则将其添加到该对象中

标签 javascript json

我有这个 JSON 对象:

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

我有一个方法可以更新并返回集合,例如:

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

假设方法调用是这样的:

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

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

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

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

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

最佳答案

创建一个仅包含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;
  }

关于javascript - 如果 JSON 对象不存在,则将其添加到该对象中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55295273/

相关文章:

javascript - 使用 javascript、php 和 json 在 html 中动态选择标签

javascript - 如何在 tsconfig.json 中设置 'language_in' 选项?

javascript - 如何使用 VM 在 nodejs 中安全地运行用户代码而不容易受到攻击

json - 使用 Spark 和 scala 从 Spark 数据帧中的 JSON 类型列中获取所有值,而不考虑键

java - Json:使用 Gson 库时出现反序列化错误

javascript/json 存储严格索引的数组

php - laravel 4.1 用数据库中的数据填充表格

javascript - AngularJS 选择 ng-options 不会更新父范围中引用的对象属性

javascript - 未根据 ReactJS 状态更改检查单选按钮

javascript - 使用 IE9 访问网站时出现 "SCRIPT28: Out of stack space"