'How to add two array of objects as one array of object react
Hello Everyone I am new to javascript and ReactJs. Can someone guide me How can I combine two or more array of objects as one array of object in react or javascript.
here is e.g:
Object1: [
{
cell: 2225,
name: "abc",
add: "Hell",
city: "York",
id: 1
},
{
cell: 1425,
name: "Bol",
add: "Lem",
city: "York",
id: 2
}
.
.
]
Object2: [
{
cell: 3334,
name: "Zak",
add: "NewY",
city: "NewY",
id: 1
},
{
cell: 444,
name: "Sachin",
add: "Mum",
city: "Lon",
id: 2
}
.
.
]
result I am expecting:
Object3: [
{
cell: 2225,
name: "abc",
add: "Hell",
city: "York",
id: 1
},
{
cell: 1425,
name: "Bol",
add: "Lem",
city: "York",
id: 2
},
{
cell: 3334,
name: "Zak",
add: "NewY",
city: "NewY",
id: 1
},
{
cell: 444,
name: "Sachin",
add: "Mum",
city: "Lon",
id: 2
}
]
I know its simple but its new for me,I checked some example on stackoverflow and other site but didn't understand.Can someone give me the simpe example how can i achieve this.In my case i dont want to avoid duplicate object it should be add as it is.
Thanks for any help!
Solution 1:[1]
This is how you wanted.
let Arr = {
Object1: [
{
cell: 2225,
name: "abc",
add: "Hell",
city: "York",
id: 1
},
{
cell: 1425,
name: "Bol",
add: "Lem",
city: "York",
id: 2
}
],
Object2: [
{
cell: 3334,
name: "Zak",
add: "NewY",
city: "NewY",
id: 1
},
{
cell: 444,
name: "Sachin",
add: "Mum",
city: "Lon",
id: 2
}
]
};
let Object3 = [];
Object3.push(...Arr.Object1, ...Arr.Object2);
console.log(Object3);
Solution 2:[2]
Try this
let Object1 = [
{
cell: 2225,
name: "abc",
add: "Hell",
city: "York",
id: 1
},
{
cell: 1425,
name: "Bol",
add: "Lem",
city: "York",
id: 2
}
];
let Object2 = [
{
cell: 3334,
name: "Zak",
add: "NewY",
city: "NewY",
id: 1
},
{
cell: 444,
name: "Sachin",
add: "Mum",
city: "Lon",
id: 2
}
];
let Object3 = [...Object1, ...Object2];
console.log(Object3);
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 | Amruth |
| Solution 2 | Isuru Chandrasiri |
