lodash是否有办法,结果我没有满足特定条件的对象。例如,
o1 = [
{name: "a", id: 2, key: 33},
..,
]
o2 = [
{name: "ab", id: 2, key: 133}
]
lodash是否有一种方法,其中结果数组仅包含o2
中不存在ID的对象。例如,比较o1
和o2
之后的结果对象必须不具有o2中的对象,因为id=2
中已经存在o1
。
答案 0 :(得分:2)
您可以使用_.differenceBy()
并使用参考点的id
:
const o1 = [{id: 1, name: 'a'},{id: 2, name: 'b'},{id: 3, name: 'c'}]
const o2 = [{id: 1, name: 'b'}]
const result = _.differenceBy(o1, o2, 'id')
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
答案 1 :(得分:1)
您可以通过使用.filter()
并创建一个Set
来实现而不用破折号。首先,您可以在o2
中创建一组所有ID。然后,您可以从o1
中过滤出集合中具有ID的所有对象。通过将集合与.has()
配合使用,我们可以提高算法的效率(比对数组使用.includes()
更高。)
请参见以下示例:
const o1 = [
{name: "a", id: 2, key: 33},
{name: "b", id: 3, key: 34},
{name: "c", id: 4, key: 34}
]
const o2 = [
{name: "d", id: 2, key: 134}
]
const o2_ids = new Set(o2.map(({id}) => id));
const result = o1.filter(({id}) => !o2_ids.has(id));
console.log(result); // includes objects with id's that appear in o1 but not in o2
答案 2 :(得分:1)
也许是_.differenceWith
?
const o1 = [
{id: 1, name: "a"},
{id: 2, name: "b"},
{id: 3, name: "c"},
]
const o2 = [
{id: 1, name: "b"},
]
const diffed = _.differenceWith(o1, o2, (o1, o2) => o1.id === o2.id)
console.log(diffed)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
答案 3 :(得分:0)
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
var o1 = [
{name: "a", id: 77, key: 55},
{name: "a", id: 2, key: 33},
{name: "a", id: 1, key: 55}
]
var o2 = [
{name: "ab", id: 88, key: 133},
{name: "ab", id: 2, key: 133},
{name: "ab", id: 99, key: 133}
]
//sort first
o1.sort((a, b) => {
return a.id-b.id;//sort by id
});
o2.sort((a, b) => {
return a.id-b.id;//sort by id
});
//then compare one by one
function SearchX(OO1,OO2){
var o1_compare_place=0;
var o2_compare_place=0;
while(OO2.length>o2_compare_place && OO1.length>o1_compare_place ){
if(OO2[o2_compare_place].id<OO1[o1_compare_place].id){
o2_compare_place+=1;
}else if(OO2[o2_compare_place].id>OO1[o1_compare_place].id){
o1_compare_place+=1;
}else{
return "Exist Same!";
}
}
return "Different!";
}
document.body.innerHTML = SearchX(o1,o2)
</script>
</body>
</html>
您在这里