javascript
I want to insert different array values per object into an array inside the object.
I have an arrayDetail
object.
console.log(arrayDetail)
[
{
"content": "stackoverflow1",
"type": "one"
"appleId": undefined
},
{
"content": "stackoverflow2",
"type": "two"
"appleId": undefined
}
]
I have an applesIds
array.
console.log(applesIds);
[49,50]
This is the result I want.
I tried a few times using map
function or Object.fromEntries()
function and looked up other stack overflow questions,
but I can't get it to work.
[
{
"content": "stackoverflow1",
"type": "one"
"appleId": 49
},
{
"content": "stackoverflow2",
"type": "two"
"appleId": 50
}
]
CodePudding user response:
You can use Array.map
(use can use other Array iteration methods as well) and update the appleId like below
const arrayDetail = [{
"content": "stackoverflow1",
"type": "one",
"appleId": undefined
},
{
"content": "stackoverflow2",
"type": "two",
"appleId": undefined
}
]
const appleIds = [49, 50];
const result = arrayDetail.map((item, index) => {
return { ...item,
appleId: appleIds[index]
}
});
console.log(result);
CodePudding user response:
This would do the work
let data = [
{
"content": "stackoverflow1",
"type": "one",
"appleId": undefined
},
{
"content": "stackoverflow2",
"type": "two",
"appleId": undefined
}
]
let id = [49, 50]
for(let i = 0; i < data.length; i ){
data[i]['appleId'] = id[i]
}
console.log(data)
CodePudding user response:
Single liner code map always return array so i was returning array of object and put appleId with the help of index. index is 0,1,2 iteration so access id array with index
const mappedData = data.map((item, index) => ({ ...item, appleId: id[index] }));