【问题标题】:Append one object to another one [duplicate]将一个对象附加到另一个对象[重复]
【发布时间】:2018-10-11 16:09:03
【问题描述】:

我有两个 JSON 对象,我想将 newData 附加到现有数据中。

existingData = {"School Name" : "Albert"}
newData = {"Teacher Name" : "Ms. Mithcell"}

这是我想要的输出:

existingData = {"School Name" : "Albert" , "Teacher Name" : "Ms. Mithcell"};

我该怎么做?

【问题讨论】:

  • 你用谷歌搜索了吗?提示:搜索“合并 javascript 对象”。

标签: javascript json


【解决方案1】:

对于 javascript,它的 object 不是 python 像 dictionary :P,只需使用 Spread 语法即可完成工作。

existingData = {"School Name" : "Albert"}
newData = {"Teacher Name" : "Ms. Mithcell"}
result = {...existingData, ...newData};
console.log(result);

【讨论】:

    【解决方案2】:

    Javascript 有 Object.assign 函数。

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

    existingData = {"School Name" : "Albert"}
    newData = {"Teacher Name" : "Ms. Mithcell"}
    
    Object.assign(existingData, newData) 
    
    console.log(existingData); // {School Name: "Albert", Teacher Name: "Ms. Mithcell"}
    

    Object.assign( originalObject, newObject ) 将返回 originalObject 并将 newObject 合并到其中。

    【讨论】:

      【解决方案3】:

      您可以这样做以获得更正统的方法:

      existingData = {"School Name" : "Albert"};
      newData = {"Teacher Name" : "Ms. Mithcell"};
      
      var new_keys = Object.keys(newData);
      
      for (var i = 0; i < new_keys.length; i++){
        existingData[new_keys] = newData[new_keys[i]];
      }
      
      console.log(existingData);

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-04-15
        • 1970-01-01
        • 1970-01-01
        • 2010-11-29
        • 1970-01-01
        • 2014-06-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多