I would not be able to make the following code add an ID to each object within the first array
const people=[
{first_name:"john",last_name:"doe"},
{first_name:"mary",last_name:"beth"}
];
const id = ['abc' ,'xyz']
for(const x in id){
for(const y in people){
people[y].id = id[x]
}
}
console.log(people)
This returns:
[
{ first_name: 'john', last_name: 'doe', id: 'xyz' },
{ first_name: 'mary', last_name: 'beth', id: 'xyz'}
]
What would be the most appropriate way to be able to assign a new key/value to each object respecting the values of the second array ?
I would propose you to use array.map and use the index of the array itself to take the values of the second, in this way:
The first loop
for
iterates a total of two times. In the first iteration, assign the value1
toid
each person, in the second iteration, assign the value2
, so that you are overwriting the same value.One way to do it would be declaring a counter that increments when assigning the value of
id
:If you want the to
id
come from an array, you can use that same counter to assign the value of the array to it. This assigns the values consecutively.If you don't need to create a new array, I would use a classic for:
In another case, you could use a map, as @AngelCordones recommends in his answer, but I would create a new object to actually leave the original array the same:
The for
people
insideid
loops through all the records ofpeople
for each element ofid
, so it will always be the last one, assigns all the values and stays the last one because it is not overwritten by anything. Actually, for each thereid
corresponds anpeople
apparently in the same order, so the correct thing would be to do a single iteration. They have given you several examples, I leave you one using the spread operator to join the objects, which makes it quite short: