Is there a method to add and an arry of objects to the end of an array of objects without makeing a for loop?

Issue

Im trying to add an object to the end of another object but the methods im finding add extra keys I dont want. Here is what im looking for:

let obj1 = [{"d": "1", "t": "1"}, {"d": "2", "t": "2"}]
let obj2 = [{"d": "3", "t": "3"}, {"d": "4", "t": "4"}]

desired output =
[{"d": "1", "t": "1"}, {"d": "2", "t": "2"}, {"d": "3", "t": "3"}, {"d": "4", "t": "4"}]

Alternatively if there is a way to add and object in the middle of another that would be fantastic but i havent found a way to do that yet so spliting then pushing then adding back together is my work arround.

let obj1 = [{"d": "1", "t": "1"}, {"d": "2", "t": "2"}, {"d": "4", "t": "4"}]
let obj2 = [{"d": "3", "t": "3"}]

desired output =
[{"d": "1", "t": "1"}, {"d": "2", "t": "2"}, {"d": "3", "t": "3"}, {"d": "4", "t": "4"}]

Edit:
Ive previously tride obj1.push(obj2) which returns:

[{"d": "1", "t": "1"},{"d": "2", "t": "2"}[{"d": "3", "t": "3"},{"d": "4", "t": "4"}]]

And obj3 = {obj1, obj2} which returns:

{obj1: [{"d": "1", "t": "1"},{"d": "2", "t": "2"}],obj2: [{"d": "3", "t": "3"},{"d": "4", "t": "4"}]}

And obj3 = {…obj1, …obj2} and idk whats going on here:

{
  '0': {"d": "3", "t": "3"},
  '1': {"d": "4", "t": "4"},
  '2': {"d": "2", "t": "2"}
}

Solution

I would use the spread syntax ...

const obj1 = [{"d": "1", "t": "1"}, {"d": "2", "t": "2"}]
const obj2 = [{"d": "3", "t": "3"}, {"d": "4", "t": "4"}]
const obj3 = [...obj1, ...obj2]

console.log(obj3)

Answered By – Asleepace

Answer Checked By – David Goodson (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.