Filter objects in array by key-value pairs

余生颓废 提交于 2021-01-29 08:12:05

问题


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)


回答1:


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))



回答2:


If I understand your question correctly, startsWith is the key term you looking for?

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

const searchTerm = { id: 'a', name: 'al' }
const result = arr.filter(x => 
                x.id === searchTerm.id || 
                x.name.startsWith(searchTerm.name)
              );
              
console.log(result)



回答3:


You can create a custom method that receives and object with pairs of (key, regular expression) and inside the Array.filter() iterater over the Object.entries() to check for some match.

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

const filterWithSome = (arr, obj) =>
{
    return arr.filter(o =>
    {
        return Object.entries(obj).some(([k, v]) => o[k].match(v));
    });
}

console.log(filterWithSome(input, {id: /^a/, name: /^al/}));
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

If you instead want a match on every (key, regular expression) of the object passed as argument, then you can replace Array.some() by Array.every():

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

const filterWithEvery = (arr, obj) =>
{
    return arr.filter(o =>
    {
        return Object.entries(obj).every(([k, v]) => o[k].match(v));
    });
}

console.log(filterWithEvery(input, {id: /^ab/, name: /^al/}));
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}



回答4:


For the dynamic object filter. You can you closure and reduce

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

const queryObj = { id: 'a', name: 'al' }
const queryObj2 = { name: 'al', age: 13 }

const filterWith = obj => e => { 
  return Object.entries(obj).reduce((acc, [key, val]) => {
    if(typeof val === 'string') return acc || e[key].startsWith(val)
    else return acc || e[key] === val
  }, false)
}

const filter1 = filterWith(queryObj)
const filter2 = filterWith(queryObj2)

console.log(data.filter(filter1))
console.log(data.filter(filter2))


来源:https://stackoverflow.com/questions/55485823/filter-objects-in-array-by-key-value-pairs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!