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', la...

问题:

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?


回答1:

The shortest one that I personally could imagine.

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

回答2:

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


回答3:

return options.map(v => {
  let newObj = {};
  newObj[v.value] = selected.find(option => { return 
  option.value == v.value }) !== undefined;
  return newObj;
})
  • 发表于 2019-03-02 04:16
  • 阅读 ( 170 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除