js 一个数组和一个数组对象,获取两个之间不同的元素和相同的元素?

segmentfault 2022-08-06 19:11:43 阅读数:932

JS数组一个个数
var value = '';
var list = ['a', 'b', 'c', 'e'];
var list2 = [{ id: 1, name: 'a' }, { id: 1, name: 'c' }, { id: 1, name: 'd' }];

想要的效果是

var list3 = [{ id: 1, name: 'a', checked: true }, { id: 1, name: 'c', checked: true }, { id: 1, name: 'd' }]
value = 'b,e';

把list2中与list的相同的对象多加一个元素checked, 然后把不相同的用字符串打印出来.



其他答案1:
var value = '';
var list = ['a','b','c','e'];
var list2 = [{id:1,name:'a'},{id:1,name:'c'},{id:1,name:'d'}];
let idxArr = [];
let list3 = JSON.parse(JSON.stringify(list2));;
list3.map(item=>{
let idx = list.indexOf(item.name);
if(idx > -1){
idxArr.push(idx);
item.checked = true;
}
return item;
});
value = list.filter((item,idx)=>idxArr.indexOf(idx) < 0).join(",");

其他答案2:
var value = list.reduce((a,b) => list2.find(v => v.name === b)?a:[...a,b],[]);
var list3 = list2.reduce((a, b) => [...a, { ...b, checked: list.includes(b.name) }], []);

其他答案3:
const list3 = list2.map((it) => list.includes(it.name) ? { ...it, checked: true } : { ...it });
const value = list.filter(name => !list3.find(it => it.name === name));
版权声明:本文为[segmentfault]所创,转载请带上原文链接,感谢。 https://segmentfault.com/q/1010000042259120