1

I have 2 object arrays

const options = [
  { value: 'opt1', label: 'opt1' },
  { value: 'opt2', label: 'opt2' },
  { value: 'opt3', label: 'opt3' },
  { value: 'opt4', label: 'opt4' }
]

const selected = [
  { value: 'opt1', key: '1' },
  { value: 'opt2', key: '2' }
]

I need to compare these two arrays and get result as

result =
  { 'opt1', true },
  { 'opt2', true },
  { 'opt3', false },
  { 'opt4', false }
]

since opt1 and opt2 exists in second array. I know there are lots of methods, but what would be the shortest method?

3 Answers 3

1

The shortest one that I personally could imagine.

const result = options.map(o => ({ [o.value]: !!selected.find(s => s.value === o.value) }));
Sign up to request clarification or add additional context in comments.

Comments

1

You can use the function map to get the mapped values first of the selected and then a map the array options using a logic to ask for the existence of a value within the selected array. Finally, use computed-property-names to build the desired output.

const options = [  { value: 'opt1', label: 'opt1' },  { value: 'opt2', label: 'opt2' },  { value: 'opt3', label: 'opt3' },  { value: 'opt4', label: 'opt4' }],
      selected = [  { value: 'opt1', key: '1' },  { value: 'opt2',key: '2' }],
      mapped = selected.map(({value}) => value),
      result = options.map(({value}) => ({[value]: mapped.includes(value)}));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Comments

1
return options.map(v => {
  let newObj = {};
  newObj[v.value] = selected.find(option => { return 
  option.value == v.value }) !== undefined;
  return newObj;
})

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.