如何通过另一个对象数组过滤对象数组

如何通过另一个对象数组过滤对象数组

本文介绍了如何通过另一个对象数组过滤对象数组[ES6]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在不知道条件数组中确切属性的情况下,用另一个对象数组过滤对象数组.让我们看一下示例以更好地理解.

I need to filter array of object by another array of object without knowledge of exact properties in criterias array. Let's take a look to example for better understanding.

这是我需要过滤的数组

const dataset = [
{
  id: "4",
  someval1: "10",
  someval2: "20",
  someval3: "30",
  someval4: "40"
},
{
  id: "10",
  someval1: "10",
  someval2: "20",
  someval3: "30",
  someval4: "40"
},
{
  id: "22",
  someval1: "102",
  someval2: "202",
  someval3: "302",
  someval4: "40"
}];

这是一个数组,其值应该是第一个数组的过滤条件

Here is an array which has values that are supposed to be filter condition for first array

const criterias = [{ someval1: "10" }, { someval3: "30" }, { someval4: "40" }];

因此,只要 dataset 中的对象包含 criterias 中的所有值,我都希望保留它.问题是我希望数据集中的对象被所有相等的条件过滤.

So whenever object in dataset contains all values from criterias I want to keep him. Problem is that I want objects in dataset to be filtered by all criterias that are equal.

到目前为止,我已经能够获得此脚本,该脚本正确过滤了 dataset ,但仅过滤了一个 criteria .因此,从过滤后的给定数组中,我应该仅从 dataset 中获得两个对象,第三个对象不能满足所有 criterias .

So far I was able to get this script which filters dataset correctly but only by one criteria. So from given arrays after filtering I should get only first two objects from dataset, third one does not meat all criterias.

这是我当前的脚本

const dataset = [
{
  id: "4",
  someval1: "10",
  someval2: "20",
  someval3: "30",
  someval4: "40"
},
{
  id: "10",
  someval1: "10",
  someval2: "20",
  someval3: "30",
  someval4: "40"
},
{
  id: "22",
  someval1: "102",
  someval2: "202",
  someval3: "302",
  someval4: "40"
}];

const criterias = [{ someval1: "10" }, { someval3: "30" }, { someval4: "40" }];

const filter = dataset.filter(item => criterias.some(criteria => Object.keys(criteria).some(prop => item[prop] != criteria[prop])));

console.log(filter)

感谢所有建议.

推荐答案

您可以获取压缩对象的条目并使用 Array#every 并使用值检查属性.

You could get the entries of the condensed object and use Array#every and check the properties with the values.

var dataset = [{ id: "4", someval1: "10", someval2: "20", someval3: "30", someval4: "40" }, { id: "10", someval1: "10", someval2: "20", someval3: "30", someval4: "40" }, { id: "22", someval1: "102", someval2: "202", someval3: "302", someval4: "40" }],
    criterias = [{ someval1: "10" }, { someval3: "30" }, { someval4: "40" }],
    filters = Object.entries(Object.assign({}, ...criterias)),
    result = dataset.filter(o => filters.every(([k, v]) => o[k] === v));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

这篇关于如何通过另一个对象数组过滤对象数组[ES6]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 18:23