从另一个数组中过滤出一个数组 [英] Filter out an array from another array

查看:329
本文介绍了从另一个数组中过滤出一个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有2个对象数组,看起来像这样

So I have 2 arrays of objects, it looks like this

    this.balanceCodes = [
        { ID: 1, StringValue: "dummy" },
        { ID: 2, StringValue: "data" }
    ];
    this.allCodes = [
        { ID: 1, StringValue: "dummy", Color: "red", Order: "low" },
        { ID: 2, StringValue: "data", Color: "green", Order: "medium" },
        { ID: 3, StringValue: "extra", Color: "black", Order: "low" },
        { ID: 4, StringValue: "options", Color: "grey", Order: "high" }
    ];

我想过滤出this.balanceCodes中的对象(基于ID)

I want to filter out the objects that are in this.balanceCodes (based on ID)

因此,期望的结果将是:

So the desired result would be:

    this.result = [
        { ID: 3, StringValue: "extra", Color: "black", Order: "low" },
        { ID: 4, StringValue: "options", Color: "grey", Order: "high" }
    ];

我该如何实现?我知道我可以轻松过滤出一个对象,但是如何对整个对象数组进行过滤呢?

how can I achieve this? I know I can easily filter out an object, but how can I do this for an entire array of objects?

我可以使用Lodash.

I'm allowed to use Lodash.

推荐答案

使用 _.differenceBy() 在第一个数组(allCodes)中查找在第二个数组(balanceCodes)中找不到的项目:

Use _.differenceBy() to find items in the 1st array (allCodes) that are not found in the 2nd array (balanceCodes):

var balanceCodes = [
    { ID: 1, StringValue: "dummy" },
    { ID: 2, StringValue: "data" }
];
var allCodes = [
    { ID: 1, StringValue: "dummy", Color: "red", Order: "low" },
    { ID: 2, StringValue: "data", Color: "green", Order: "medium" },
    { ID: 3, StringValue: "extra", Color: "black", Order: "low" },
    { ID: 4, StringValue: "options", Color: "grey", Order: "high" }
];

var result = _.differenceBy(allCodes, balanceCodes, 'ID');

console.log(result);

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

这篇关于从另一个数组中过滤出一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆