I have two arrays of objects (10 objects in each arrray) ->
arr1 = [{name: '', age: ''}...]
and
arr2 = [{surname: '', position: ''}...]
which I hold in two separated states. My goal is to create the third array of the objects which contains also 10 elements
arr3=[{name: arr1.name, surname: arr2.surname}...]
How can I do this ?
CodePudding user response:
As long as it is a 1 to 1 where each index matches, it is a simple Array map and using the spread to copy over the properties and values.
const arr1 = [{a: 1, b: 2}, {a: 3, b: 4}];
const arr2 = [{c: 11, d: 22}, {c: 33, d: 44}];
const arr3 = arr1.map((obj, ind) => ({...obj, ...arr2[ind]}), []);
console.log(arr3);
CodePudding user response:
This is what you need,
let arr3 = []
arr1.forEach((obj1, index) => {
let obj3 = {...obj1, ...arr2[index]}
arr3.push(obj3)
})
CodePudding user response:
If the indexes are assumed to match between the two arrays (which also implies that the two arrays are the same length), you can use map()
on one array and use its index parameter to reference the other array. (It doesn't really matter which.)
For example:
const arr3 = arr1.map((a, i) => ({
name: a.name,
surname: arr2[i].surname
}));
Note that this is based on the example shown, where only two properties (one from each array) are in the resulting objects. If you want all properties in the resulting objects, you don't need to specify all of them. You can just combine them all:
const arr3 = arr1.map((a, i) => ({
...a,
...arr2[i]
}));
CodePudding user response:
const arr3 = []
for (let i = 0; i < arr1.length; i ) {
arr3[i] = {
name: arr1[i].name,
surname: arr2[i].surname
}
}
CodePudding user response:
I don't get exactly what do you want to do but I think this question has been answered a few times.
You wanna do arr1 arr2 ? Like they follow each others in the array3 ?