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!
CodePudding user response:
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);
CodePudding user response:
Try something like this
const C = A.map((value, idx) =>({
...value,
score: B[idx],
}));
console.log(C)
CodePudding user response:
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]
}
}
))
CodePudding user response:
The input Data Structure is not really good... What if array don't have the same size ?
With your data model:
var A = [
{id: 1, name: "han"},
{id: 2, name: "mohd"},
]
var B = [100, 200];
Object.entries(A).map((entry,i) => {
return {
...entry[1], //Object from A
score: B[i] // Get I index from B
}
})
Ideal DataModel
var B = [
{id: 1, score:100 },
{id: 2, score:200 }
]
and merge A an B with id.
CodePudding user response:
You try with that method.
let A = [
{id: 1, name: "han"},
{id: 2, name: "mohd"},
]
let B = [100, 200];
let newArray = [];
let newObj ={};
for(let i=0;i<A.length;i ){
for(let j=0;j<B.length;j ){
newObj = Object.assign(A[i],{score: B[j]})
}
newArray.push(newObj);
}
console.log(newArray);