0

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
}]
2
  • The string array isn't one; that is an object array. Should it be ['fghij','klmno'] ? Commented Mar 1, 2017 at 13:02
  • Sorry, typo on my part Commented Mar 1, 2017 at 13:55

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

5 Comments

It works partialy, returning the following: [ { "checked": false }, { "checked": true }, { "checked": true } ] - none of the other data was mapped.
Are you targeting ES6? Object.assign is basically doing a shallow "merge" of two objects but is only available in ES6. If not you must get a polyfill
I have set-up a Typescript playground so that you can see it running. See edit above
Thanks, I had an extra parenthesis at the end which caused only checked to return
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.