Taahir Hassem
Taahir Hassem

Reputation: 147

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
}]

Upvotes: 0

Views: 60

Answers (2)

Bruno Grieder
Bruno Grieder

Reputation: 29814

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 })

Upvotes: 2

Tamas Hegedus
Tamas Hegedus

Reputation: 29906

I would suggest to collect the values in an ES6 Set object for code clarity and performance reasons.

Basically you have two option here: modify the array in place, or copying it. Example for both:

const data = [{
    name: 'ABCDE',
    value: 'abcde',
    checked: false
}, {
    name: 'FGHIJ',
    value: 'fghij',
    checked: false
}, {
    name: 'KLMNO',
    value: 'klmno',
    checked: false
}];

const toCheck = [ 'fghij', 'klmno' ];


const toCheckSet = new Set(toCheck);

// copying the data
const newData = data.map(obj => ({
    name: obj.name,
    value: obj.value,
    checked: toCheckSet.has(obj.value)
}));
console.log(newData);

// altering in place:
data.forEach(obj => { obj.checked = toCheckSet.has(obj.value); })
console.log(data);

Upvotes: 0

Related Questions