【问题标题】:Adding object to an existing object using Javascript [duplicate]使用Javascript将对象添加到现有对象[重复]
【发布时间】:2020-07-13 03:03:34
【问题描述】:

我正在寻找 jQuery / javascript 中的解决方案来将对象添加到 objectArray。 在我的对象中,我有对象“objectArray”。此元素内部是动态数量的其他对象。

如何添加,即这个对象:

{
        "code": "7891",
        "items": {
          "attribute": "car",
        }

到对象数组而不覆盖第一个元素?要得到这个:

"objectArray": [
  {
    "code": "1234",
    "items": {
      "attribute": "House",
    }
  },
  {
    "code": "7891",
    "items": {
      "attribute": "car",
    }
  },
],

我使用了数组和 JSON.stringify() 的方式,但这并不好用。

【问题讨论】:

    标签: javascript jquery arrays json object


    【解决方案1】:

    您可以使用objectArray.push(object)object 附加到数组中。

    更多信息请点击此处:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push

    【讨论】:

      【解决方案2】:

      const data = [
        {
          code: "7891",
          items: {
            attribute: "car"
          }
        }
      ];
      const res = [
        {
          code: "1233",
          items: {
            attribute: "car"
          }
        },
        ...data
      ];
      
      //Or
      const res2 = [
        {
          code: "1233",
          items: {
            attribute: "car"
          }
        }
      ].concat(data);
      
      console.log(res, res2);

      【讨论】:

      • 请不要只提供代码,而是添加对其功能的描述。
      • 明白。谢谢!但不是push,升档
      猜你喜欢
      • 1970-01-01
      • 2021-09-06
      • 2015-09-18
      • 2010-12-17
      • 1970-01-01
      • 1970-01-01
      • 2012-08-27
      • 2016-04-20
      • 1970-01-01
      相关资源
      最近更新 更多