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.

0

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

-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);

2 Comments

Please don't just provide code, but instead add a description to what it does.
Understand. Thanks! But it was not push, upshift

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.