我有两个数组对象,我想比较它们并从两个数组中删除值是否匹配。
Arr1 = [
{id: "one", name: "one", status: "Active"},
{id: "two", name: "two", status: "Active"},
{id: "three", name: "three", status: "Active"}
]
Arr2 = [
{pid: "one", order: 1},
{pid: "two", order: 2}
]
现在我想要如果id === pid
它不应该返回。
finalArr = [
{id: "three", name: "three", status: "Active"}
]
我尝试了下面的解决方案,但不知何故它不起作用,它返回空数组。
finalArr = Arr1.filter((a) => {
Arr2.some((b) => {
a['id'] === b['pid'];
});
});
如果您需要更多信息,请告诉我。我希望我能够表达我的关切。 4
谢谢!
由于您标记了lodash,您可以考虑使用该_.differenceWith()
方法,该方法允许您提供一个比较器函数来指定您应该通过什么属性来获取差异。但是,如果您还没有使用 lodash,那么最好使用 vanilla 方法。
const arr1 = [{id: "one", name: "one", status: "Active"}, {id: "two", name: "two", status: "Active"}, {id: "three", name: "three", status: "Active"}];
const arr2 = [{pid: "one", order: 1}, {pid: "two", order: 2}];
const res = _.differenceWith(arr1, arr2, ({id}, {pid}) => id === pid);
console.log(res); // [{ "id": "three", "name": "three", "status": "Active" }]
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句