Kimaya
Kimaya

Reputation: 1420

compare 2 object arrays and return the elements in first array as true if it exists in second array, or as false if it does not

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?

Upvotes: 1

Views: 54

Answers (3)

Arfeo
Arfeo

Reputation: 867

The shortest one that I personally could imagine.

const result = options.map(o => ({ [o.value]: !!selected.find(s => s.value === o.value) }));

Upvotes: 1

Joshua Paul Huang
Joshua Paul Huang

Reputation: 123

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

Upvotes: 1

Ele
Ele

Reputation: 33726

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

Upvotes: 1

Related Questions