1

I have the following object:

[
    { id: 1 },
    { id: 2 },
    { id: 3 }
]

And I wanna add a another array but just to the last array of the object, always (the first object length can change). So, it might look like this:

New array element:

{ name: "Hello Id 3" }

First object with the the second one appended:

[
    { id: 1 },
    { id: 2 },
    { id: 3, name: "Hello Id 3" }
]

Any ideas?

Thanks in advance!

2 Answers 2

2

Using Object.assign() is one way to merge properties of two objects

const data = [
    { id: 1 },
    { id: 2 },
    { id: 3 }
]

const obj = { name: "Hello Id 3" };

Object.assign( data[data.length-1], obj);

console.log(data)

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

1 Comment

Both answers are excellent, but I choose this one for it's practicality.
1

You can use Array.length (-1) to find the index of the last object in the array and then add the elements of the new object to that:

let objs = [
    { id: 1 },
    { id: 2 },
    { id: 3 }
];

const name = { name: "Hello Id 3" };

const idx = objs.length - 1;
objs[idx] = { ...objs[idx], ...name };
console.log(objs);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.