i want to add a field type to each object in an array and push the result to another array and push that to another array.
below is how the array of object looks,
const arrObj1 = [
{
id: '1',
name: 'n1',
},
{
id: '2',
name: 'n2',
}
]
const arrObj2 = [
{
id: '3',
name: 'n3',
},
{
id: '4',
name: 'n4',
}
]
what i am trying to do?
i want to add a type field with value 'type1' to arrObj1 and type field with value 'type2' to arrObj2
so the output should be like below,
const arrObj1 = [
{
id: '1',
name: 'n1',
type: 'type1',
},
{
id: '2',
name: 'n2',
type: 'type1',
}
]
const arrObj2 = [
{
id: '3',
name: 'n3',
type: 'type2',
},
{
id: '4',
name: 'n4',
type: 'type2',
}
]
then i want to combine these two arrays arrObj1 and arrObj2 into one array like below
const combinedArrObj = [
{
id: '1',
name: 'n1',
type: 'type1',
},
{
id: '2',
name: 'n2',
type: 'type1',
},
{
id: '3',
name: 'n3',
type: 'type2',
},
{
id: '4',
name: 'n4',
type: 'type2',
}
]
what i have tried?
const arrObj1Res = arrObj1.map((obj: any) => {
return {
...arrObj1,
type: 'type1',
}
});
const arrObj2Res = arrObj2.map((obj: any) => {
return {
...arrObj2,
type: 'type2',
}
});
const combinedArrObj = [
...arrObj1Res,
...arrObj2Res,
];
this works. but how can i refactor to something simple rather than adding field type for each obj in array and then combine
could someone help me with this. thanks.
question from:
https://stackoverflow.com/questions/65920645/how-to-add-a-field-to-each-object-in-array-and-push-that-result-array-to-another