1

I am looking for a solution in jQuery / javascript to add an object to an objectArray. In my object I have the object "objectArray". Inside of this elment is a dynamic number of other objects.

How can I add i.e. this object:

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

To the object Array without overwritting the frist element? To get this:

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

I used the way with arrays and JSON.stringify() but this doesn't work well.

Thomas
  • 19
  • 3

2 Answers2

2

You can do objectArray.push(object) which appends the object to the array.

More info on that here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push

sportzpikachu
  • 831
  • 5
  • 18
-1

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);
xdeepakv
  • 7,835
  • 2
  • 22
  • 32