[英]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 我有2个对象数组
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. 因为opt1和opt2存在于第二个数组中。 I know there are lots of methods, but what would be the shortest method?
我知道有很多方法,但最短的方法是什么?
我个人可以想象的最短的一个。
const result = options.map(o => ({ [o.value]: !!selected.find(s => s.value === o.value) }));
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. 您可以使用函数
map
首先获取所选映射值,然后使用逻辑映射数组options
以询问selected
数组中是否存在值。 Finally, use computed-property-names
to build the desired output. 最后,使用
computed-property-names
来构建所需的输出。
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; }
return options.map(v => {
let newObj = {};
newObj[v.value] = selected.find(option => { return
option.value == v.value }) !== undefined;
return newObj;
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.