[英]How filter array of objects based on objects exists in another array of objects?
I have我有
array1 = [{ name: sample1 }, { name: sample2 }, { name: sample3 }];
array2 = [{ name: sample1 }, { name: sample2 }];
I want to filter objects of array1
which exists in array2
.我想过滤
array2
中存在的array1
对象。 So I need to have所以我需要有
[{ name: sample1 }, { name: sample2 }]
How can I get it in javascript? javascript怎么弄到?
I guess your objects are not referentially same, so you can try stringifying them and then comparing.我猜您的对象在引用上并不相同,因此您可以尝试对它们进行字符串化然后进行比较。
![]()
const array1 = [{ name: "sample1" }, { name: "sample2" }, { name: "sample3" }]; const array2 = [{ name: "sample1" }, { name: "sample2" }]; const jsonArr = array2.map((arr) => JSON.stringify(arr)); const res = array1.filter((obj) => jsonArr.includes(JSON.stringify(obj))); console.log(res);<\/code><\/pre>
Using a
Set<\/code> should be better in terms of performance.
使用
Set<\/code>在性能方面应该更好。
![](/img/trans.png)
const array1 = [{ name: "sample1" }, { name: "sample2" }, { name: "sample3" }]; const array2 = [{ name: "sample1" }, { name: "sample2" }]; const jsonSet = new Set(array2.map((arr) => JSON.stringify(arr))); const res = array1.filter((obj) => jsonSet.has(JSON.stringify(obj))); console.log(res);<\/code><\/pre>
![](/img/trans.png)
Note:<\/strong> With this stringify approach the order of properties do matter.注意:<\/strong>使用这种字符串化方法,属性的顺序很重要。 If order of properties can vary then you can consider using a library like lodash<\/a> .
如果属性的顺序可能不同,那么您可以考虑使用像
lodash<\/a>这样的库。
![](/img/trans.png)
"
You can use .filter and .some function in JavaScript , Here is the example您可以在 JavaScript 中使用 .filter 和 .some 函数,这是示例
const array1 = [{ name: "sample1" }, { name: "sample2" }, {
name: "sample3" }];
const array2 = [{ name: "sample1" }, { name: "sample2" }];
let Result = array1.filter(function(obj) {
return array2.some(function(obj2) {
return obj.name== obj2.name;
});
});
console.log(Result)
You can use object destructuring, the map()<\/code> and
.includes()<\/code> methods as shown below:
您可以使用对象解构、
map()<\/code>和
.includes()<\/code>方法,如下所示:
![](/img/trans.png)
const array1 = [{ name: "sample1" }, { name: "sample2" }, { name: "sample3" }]; const array2 = [{ name: "sample1" }, { name: "sample2" }]; const filtered = array1.filter( ({name}) => array2.map(o => o.name).includes(name) ); console.log( filtered );<\/code><\/pre>
"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.