【问题标题】:How can I merge a new object to existing object in an array in javascript?如何将新对象合并到javascript数组中的现有对象?
【发布时间】:2019-05-14 06:49:51
【问题描述】:

我有上面的数组。我想将{"temperature":{"work":30,"home":24}} 对象输入到数组的第一个。

所以数组应该以:

开头
0 : {title : "tptp", {"temperature":{"work":30,"home":24}}, lastview:"12-12 21:2"}

我的代码是

console.log("below is home");
console.log(this.home);
console.log(this.home[0].push({"temperature": {"work":30,"home":24}}));

但我有错误TypeError: this.home[0].push is not a function。

【问题讨论】:

  • home[0] 是一个对象 - 是否要合并这些对象?
  • 我的错。我没有看到您实际上想要合并对象。
  • this.home[0] 可能不是数组

标签: javascript arrays typeerror


【解决方案1】:

你能做的是,

this.home[0].put("temperature": {"work":30,"home":24});

【讨论】:

    【解决方案2】:

    push 函数适用于Array,不适用于Object 和

    {title : "tptp", {"temperature":{"work":30,"home":24}}, lastview:"12-12 21:2"} // Ivalid Json
    

    您必须根据您的要求插入新密钥temperature。

    console.log("below is home");
    console.log(this.home);
    this.home[0]["temperature"] = {"work":30,"home":24};
    console.log( this.home[0] );
    

    输出将是

    [
      {
        "title": "tptp",
        "lastview": "12-12 21:2",
        "temperature": {
          "work": 30,
          "home": 24
        }
      },
      {
        "title": "gngn",
        "lastview": "12-12 19:29"
      }
    ]
    

    【讨论】:

      【解决方案3】:

      您发布的预期输出是不可能的,即

      {title : "tptp", {"temperature":{"work":30,"home":24}}, lastview:"12-12 21:2"}
      

      你可能想要的是

      {title : "tptp", "temperature":{"work":30,"home":24}, lastview:"12-12 21:2"}
      

      你可以做到的

      Object.assign(this.home[0], {"temperature": {"work":30,"home":24}})
      

      【讨论】:

        猜你喜欢
        • 2023-01-16
        • 1970-01-01
        • 1970-01-01
        • 2021-12-14
        • 2022-07-22
        • 2023-01-11
        • 2021-09-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多