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?
我个人可以想象的最短的一个。
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. 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; }
return options.map(v => {
let newObj = {};
newObj[v.value] = selected.find(option => { return
option.value == v.value }) !== undefined;
return newObj;
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.