如何在JavaScript中将新对象合并到数组中的现有对象?

时间:2018-12-13 05:12:12

标签: javascript arrays typeerror

enter image description here

我有如上所述的数组。我想向数组的第一个输入 @Html.Partial("../Partial_views/_Menu_creation", new ViewDataDictionary { { "Type", "Menu" }, { "Menu", "Dimensions" }, { "Active", "Yes" }, { "Icon", "icon-1" }, { "data-hide", "" } }) In partial view @if (ViewData["Type"] == "Menu") { @if (ViewData["Active"] == "Yes") { <a data-check='@ViewData["Menu"]' role="button" class="active-menu"> <b class='@ViewData["Icon"]'></b> <span>@ViewData["Menu"]</span> </a> } else { } } @if (ViewData["Type"] == "Heading") { } This is working 对象。

因此数组应以:

开头
{"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}}));

3 个答案:

答案 0 :(得分:0)

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

{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}})

答案 1 :(得分:0)

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"
  }
]

答案 2 :(得分:-1)

您可以做的是,

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