'Is there a method to add and an arry of objects to the end of an array of objects without makeing a for loop? [closed]
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 1:[1]
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)
Solution 2:[2]
You can concat and sort your arrays:
const obj1 = [{"d": "1", "t": "1"}, {"d": "2", "t": "2"}, {"d": "4", "t": "4"}]
const obj2 = [{"d": "3", "t": "3"}]
const obj3 = obj1.concat(obj2).sort((a, b) => a.d - b.d)
console.log(obj3)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Asleepace |
| Solution 2 | Yosvel Quintero Arguelles |
