如何将数据推送到对象?

时间:2016-04-15 08:50:13

标签: javascript arrays json

我有对象,我正在尝试将数据推入其中,但我收到错误“push不是函数”。

这是我的目标:

var item = {
  "_id": {
    "$oid": "asdf976"
  },
  "Categories": [{
    "mainmodels": [{
      "submodels": [{
          "price": "2000",
          "submodelname": "lumia021",
          "Remainingphones": "0",
          "Bookedphones": "0",
          "Numofphones": "10"
        }, {
          "price": "2000",
          "submodelname": "lumia341",
          "Remainingphones": "5",
          "Bookedphones": "5",
          "Numofphones": "10"
        }

      ],
      "Status": "Active",
      "modelname": "lumia",
      "fromdate": "2016-04-01T16:39:12.051Z",
      "todate": "2016-04-31T19:19:44.051Z"
    }],
    "brand": "nokia"
  }],
  "rank": "1",
  "name": "first"
}

我想推动:

var modal = {
                'custid': '1',
                'packcode': '22'
            };
            item.push(modal);
            console.log(item);

这是我的预期结果:

var item = {
  "_id": {
    "$oid": "asdf976"
  },
  "Categories": [{
    "mainmodels": [{
      "submodels": [{
          "price": "2000",
          "submodelname": "lumia021",
          "Remainingphones": "0",
          "Bookedphones": "0",
          "Numofphones": "10"
        }, {
          "price": "2000",
          "submodelname": "lumia341",
          "Remainingphones": "5",
          "Bookedphones": "5",
          "Numofphones": "10"
        }

      ],
      "Status": "Active",
      "modelname": "lumia",
      "fromdate": "2016-04-01T16:39:12.051Z",
      "todate": "2016-04-31T19:19:44.051Z"
    }],
    "brand": "nokia"
  }],
  "rank": "1",
  "name": "first",
  'custid': '1',
  'packcode': '22'
};

我该怎么做?

1 个答案:

答案 0 :(得分:0)

你没有$_GET['action']进入对象,你push进入数组。

根据您所说的内容,您可以这样做:

push

,例如,只为对象指定属性。

在ES2015中,如果将item.custid = '1'; item.packcode = '22'; 分开,则可以使用Object.assign

modal

...但我认为此处不需要,并注意var modal = {custid: '1', packcode: '22'}; Object.assign(item, modal); modal之间没有正在进行的链接。

直播示例:

item

var item = { "_id": { "$oid": "asdf976" }, "Categories": [{ "mainmodels": [{ "submodels": [{ "price": "2000", "submodelname": "lumia021", "Remainingphones": "0", "Bookedphones": "0", "Numofphones": "10" }, { "price": "2000", "submodelname": "lumia341", "Remainingphones": "5", "Bookedphones": "5", "Numofphones": "10" } ], "Status": "Active", "modelname": "lumia", "fromdate": "2016-04-01T16:39:12.051Z", "todate": "2016-04-31T19:19:44.051Z" }], "brand": "nokia" }], "rank": "1", "name": "first" }; item.custid = '1'; item.packcode = '22'; // Note: Just using JSON for *display* document.body.innerHTML = "<pre>" + JSON.stringify(item, null, 2) + "</pre>";(需要最新的浏览器或垫片):

Object.assign