I have two array objects and want to compare them in such a way that when the symbol value in array1 matches the keyNumber in array2 then set the corresponding checked value in array1 to true.
I am using .map with both arrays but not able to get the desired result.
These are my two arrays:-
const array1 = [{
symbol: '1',
checked: false
},
{
symbol: '2',
alias: 'abc',
checked: false
},
{
symbol: '3',
alias: 'def',
checked: false
}];
const array2= [{
keyNumber: '1',
type: 'number',
},
{
keyNumber: '2',
type: 'number'
}];
Following is the code to get updated array:
const array3 = array1.map(item => {
return array2
.map(key =>
key.keyNumber === item.symbol
? { ...item, checked: true, type: key.type }
: item
)
.reduce((obj, data) => data, {});
});
console.log(array3);
I am getting only last key matched result instead of all.
array3 = [{
symbol: '1',
checked: false
},
{
symbol: '2',
alias: 'abc',
checked: true,
type: 'number'
},
{
symbol: '3',
alias: 'def',
checked: false
}];
Expected output:
array3 = [{
symbol: '1',
checked: true,
type:'number'
},
{
symbol: '2',
alias: 'abc',
checked: true,
type: 'number'
},
{
symbol: '3',
alias: 'def',
checked: false
}];