I have these array and array of objects in my React code:
var A = [
{id: 1, name: "han"},
{id: 2, name: "mohd"},
]
var B = [100, 200];
and I want to append B to A, so that the output becomes something like this:
var A = [
{id: 1, name: "han", score: "100"},
{id: 2, name: "mohd", score: "200},
]
I tried doing it with the code below:
var newArray = [];
for (let k = 0; k < A.length; k++) {
newArray = B.map(score => ({...A[k], score}));
}
return newArray;
However, the code above returns this output when console logged:
newArray = [
{id: 2, name: "mohd", score: "100"},
{id: 2, name: "mohd", score: "200},
]
It only appends the elements to the latest object, instead of to all objects. Anyone knows what is wrong with my code? Thank you!
If you're going to use map you don't also need a loop since map will iterate over the array of objects, and return new array with new objects containing the score property.
Use the second parameter of the callback - the index - to identify which element of b we should be adding as the score.
const a = [
{id: 1, name: 'han'},
{id: 2, name: 'mohd'},
];
const b = [100, 200];
// `map` over `a` making sure we get the object
// in each iteration as well as its index
const out = a.map((obj, i) => {
// Create a new object adding in the
// new `score` property using the element in `b`
// that matches the index
return { ...obj, score: b[i] };
});
console.log(out);
Try something like this
const C = A.map((value, idx) =>({
...value,
score: B[idx],
}));
console.log(C)
If your both array lenght Will same then use this method
var A = [
{id: 1, name: "han"},
{id: 2, name: "mohd"},
]
var B = [100, 200];
console.log(A.map((x,i)=>
{return {
...x,
score:B[i]
}
}
))
If not sure About use this eg..
var A = [
{id: 1, name: "han"},
{id: 2, name: "mohd"},
{id: 2, name: "mohd"},
]
var B = [100, 200];
console.log(A.map((x,i)=>
{return {
...x,
score:!B[i]?0:B[i]
}
}
))