按键值对过滤数组中的对象 [英] Filter objects in array by key-value pairs

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

问题描述

我有一个这样的对象数组:

 <代码> [{id:"a",名称:"Alan",年龄:10},{id:'ab'名称:"alanis",年龄:15},{id:"b",名称:"Alex",年龄:13}] 

我需要传递一个像 {id:'a',name:'al'} 这样的对象,以便它执行通配符过滤并返回包含前两个对象的数组.

因此,这些步骤是:

  1. 对于数组中的每个对象,从给定的过滤器对象中过滤相关的键

  2. 对于每个键,检查值是否以匹配的过滤器对象键的值开头

此刻,我正在使用lodash的过滤器功能,以便它可以进行完全匹配,但不能以匹配/通配符开头.这就是我正在做的:

filter(arrayOfObjects, filterObject)

解决方案

认为您是否正在寻找类似的东西?基本上将做一个string.includes匹配过滤器对象中每个键的值-如果其中一个键值匹配,则它将包含在结果中.如果希望整个过滤器对象匹配,则可以执行 .every ,而不是 .some ...

  const数据= [{id:"a",名称:"Alan",年龄:10},{id:"ab",名称:"alanis",年龄:15},{id:"b",名称:"Alex",年龄:13}]const filter = {id:'a',name:'al'}函数filterByObject(filterObject,data){const匹配= data.filter(object => {return Object.entries(filterObject).some(([[filterKey,filterValue])=> {返回对象[filterKey] .includes(filterValue)})})返回匹配}console.log(filterByObject(过滤器,数据)) 

I have an array of objects like so:

    [
      {
        id: 'a',
        name: 'Alan',
        age: 10
      },
      {
        id: 'ab'
        name: 'alanis',
        age: 15
      },
      {
        id: 'b',
        name: 'Alex',
        age: 13
      }
    ]

I need to pass an object like this { id: 'a', name: 'al' } so that it does a wildcard filter and returns an array with the first two objects.

So, the steps are:

  1. For each object in the array, filter the relevant keys from the given filter object

  2. For each key, check if the value starts with matching filter object key's value

At the moment I'm using lodash's filter function so that it does an exact match, but not a start with/wildcard type of match. This is what I'm doing:

filter(arrayOfObjects, filterObject)

解决方案

I think you're looking for something like this? Would basically be doing a string.includes match on the value of each key in your filter object--if one of the key values matches then it will be included in the result. If you wanted the entire filter object to match you could do .every instead of .some...

const data = [
  {
    id: 'a',
    name: 'Alan',
    age: 10
  },
  {
    id: 'ab',
    name: 'alanis',
    age: 15
  },
  {
    id: 'b',
    name: 'Alex',
    age: 13
  }
]

const filter = { id: 'a', name: 'al' }

function filterByObject(filterObject, data) {
  const matched = data.filter(object => {
    return Object.entries(filterObject).some(([filterKey, filterValue]) => {
      return object[filterKey].includes(filterValue)
    })
  })
  return matched
}

console.log(filterByObject(filter, data))

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

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