Taahir Hassem Taahir Hassem -4 years ago 200
TypeScript Question

Comparing JSON arrays for similar values in typescript

I have 2 JSON object, one is an array of strings and the other is an array of objects. I would like to check if a value from the string array exists within the object array, and if it does, set a specific value in the object array.

i.e: Given the following object array

### Object Array before
[{
name: 'ABCDE',
value: 'abcde',
checked: false
},
{
name: 'FGHIJ',
value: 'fghij',
checked: false
},
{
name: 'KLMNO'
value: 'klmno'
checked: false
}]


and given the following string array:

[ 'fghij', 'klmno' ]


the result should be the following:

### Object Array after
[{
name: 'ABCDE',
value: 'abcde',
checked: false
},
{
name: 'FGHIJ',
value: 'fghij',
checked: true
},
{
name: 'KLMNO'
value: 'klmno'
checked: true
}]

Answer Source

Something like

 arr.map( v => Object.assign(v, {checked: stringArray.indexOf(v.value) !== -1 }))

arr is the original array, stringArray contains ['fghij','klmno']

edit: Typescript Playground demonstrating it

If you do not want the original array to be modified change the assign call to Object.assign({}, v, {checked: stringArray.indexOf(v.value) !== -1 })

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download