I have array objects called heatstatus and triperrors. At this time, I want to get the value of the variable called answer, which is the sum of the objects of heatstatus and triperrors.
But when I run my code, it doesn't merge. What should I do?
this is my code
const heatstatus = [
{
equipId: "1"
},
{
equipId: "2"
},
{
equipId: "3"
},
]
const triperrors = [
{
equipId: "11",
},
{
equipId: "22",
},
{
equipId: "33",
}
]
const answer = Object.assign(heatstatus, triperrors)
// expected answer
const answer = [
{
equipId: "1",
equipId: "11",
},
{
equipId: "2",
equipId: "22",
}
{
equipId: "3",
equipId: "33",
}
]
CodePudding user response:
you can use aray.map
method on one of two array to transform each element of this array and add the missing propetry from the another one if it exist
const heatstatus = [{
equipId: "1"
},
{
equipId: "2"
},
{
equipId: "3"
},
];
const triperrors = [{
tripId: "11",
},
{
tripId: "22",
},
{
tripId: "33",
}
];
const answer = heatstatus.map((status, index) => {
return {
...status,
tripId: (triperrors[index]) ? (triperrors[index].tripId) : 'default value'
}
});
console.log(answer);
CodePudding user response:
Object.assign not merge two array, in order to get your expected results you will need to do something like this
let mainArray = (heatstatus.length>triperrors.length)? heatstatus:triperrors
let res=[];
res=mainArray.map((item,index)=>{
if(heatstatus[index] && triperrors[index]){
return {
equipId: heatstatus[index].equipId,
equipId: triperrors[index].equipId
}
}
//in case index is not present in any of array
return item;
})
CodePudding user response:
const heatstatus = [
{
equipId: "1"
},
{
equipId: "2"
},
{
equipId: "3"
},
];
const triperrors = [
{
equipId: "11",
},
{
equipId: "22",
},
{
equipId: "33",
}
];
let result = heatstatus.map((status,index)=>{
let result = {equipId:'',tripId:''};
result.equipId = status.equipId;
result.tripId = triperrors[index].equipId;
return result;
});
console.log(result)