根据单独的对象键,值过滤对象数组 [英] filter array of objects based on separate object keys, values

查看:70
本文介绍了根据单独的对象键,值过滤对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我下面有一群人:

  const FIRST_ARRAY = [
{
名称: 'Simon',
岁:32,
职业:'Student'
},
{
name:'Vera',
年龄:22,
职业:开发人员
}
];

我想过滤数组以基于过滤器对象生成单独的数组。 / p>

例如,如果我的过滤器为:

  const FILTERS = {
年龄:32岁,
名:'John',
职业:''
};

新数组应该为空,因为该数组中没有人具有32和John的组合。但是,如果我的过滤器是:

  const FILTERS = {
年龄:32,
名称:'Simon ',
职业:''
}

新一批人返回将会是:

  const NEW_ARRAY = [
{
名称:'Simon',
年龄:32岁,
职业:'学生'
}
];

如何通过遍历过滤器对象值来过滤人员数组?切记,筛选器键和值将一直动态变化。

解决方案

您可以按以下方式进行筛选:



  const FIRST_ARRAY = [{名称:'Simon',年龄:32,职业:'学生'},{名称:'Vera',年龄:22,职业:'Developer'}]; const FILTERS = {名称:'Simon',年龄:32,职业:''}; constfiltered = FIRST_ARRAY.filter(person => Object.entries(FILTERS).every(([[key,val])=> val!==''?person [key] === val:true)); console.log(已过滤);  


I have the array of people below:

  const FIRST_ARRAY = [
    {
      name: 'Simon',
      age: 32,
      occupation: 'Student'
    },
    {
      name: 'Vera',
      age: 22,
      occupation: 'Developer'
    }
  ];

I would like to filter the array to produce a separate array based on a 'filters' object.

For example if my filters are:

  const FILTERS = {
    age: 32,
    name: 'John',
    occupation: ''
  };

The new array should be empty as no people in the array have the combination of 32 and John. However if my filters are:

 const FILTERS = {
    age: 32,
    name: 'Simon',
    occupation: ''
  }

The new array of people returned will be:

 const NEW_ARRAY = [
    {
      name: 'Simon',
      age: 32,
      occupation: 'Student'
    }
  ];

How can I filter the array of people by iterating over the 'filters' object values? Bare in mind the filters keys and values will dynamically changing all the time.

解决方案

You could filter as follows:

const FIRST_ARRAY = [
  {
    name: 'Simon',
    age: 32,
    occupation: 'Student'
  },
  {
    name: 'Vera',
    age: 22,
    occupation: 'Developer'
  }
];

const FILTERS = {
  name: 'Simon',
  age: 32,
  occupation: ''
};

const filtered = FIRST_ARRAY.filter(person => Object.entries(FILTERS)
  .every(([key, val]) => val !== '' ? person[key] === val : true));
  
console.log(filtered);

这篇关于根据单独的对象键,值过滤对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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