简体   繁体   English

如何使用多个参数过滤对象数组

[英]how do I filter an array of objects using multiple parameters

I want to be able to filter an array of data by multiple parameters:我希望能够通过多个参数过滤数据数组:

const data = [{
    userId: '7',
    id: '1',
    title: 'quo provident culpa',
    body: "a",
    completed: true
  },
  {
    userId: '7',
    id: '2',
    title: 'natus commodi et',
        body: "a",
    completed: true
  },
  {
    userId: '1',
    id: '3',
    title: 'voluptatem et reprehenderit',
    body: "c",
    completed: false
  }
];

const query = {
  title: 'l',
  body: 'a'
}

I've tried this:我试过这个:

const filterData = (data, query) => {
  return data.filter(rec => {
    return Object.keys(query)
      .find(key => rec[key] === query[key])
  })
}

console.log(filterData(data, query))

My solution is not quite working since it returns any objects that satisfy at least one parameter.我的解决方案不太有效,因为它返回至少满足一个参数的任何对象。 In the case above I get this returned:在上面的例子中,我得到了这个返回:

[{
  body: "a",
  completed: true,
  id: "1",
  title: "quo provident culpa",
  userId: "7"
}, {
  body: "a",
  completed: true,
  id: "2",
  title: "natus commodi et",
  userId: "7"
}]

but what I really wanted was to get returned only what satisfies both conditions ( title and body ) by partially match the string.但我真正想要的是通过部分匹配字符串只返回满足两个条件( titlebody )的内容。 like so:像这样:

{
  userId: '7',
  id: '1',
  title: 'quo provident culpa',
  completed: true
}

I understand that the find() method returns the first element that satisfies a condition, but this was the closest I could get since I want it to我知道 find() 方法返回满足条件的第一个元素,但这是我能得到的最接近的元素,因为我希望它

You could filter with Array#every for the wanted parameters and check only with String#includes .您可以使用Array#every过滤所需的参数,并仅使用String#includes进行检查。

 const data = [{ userId: '7', id: '1', title: 'quo provident culpa', body: "a", completed: true }, { userId: '7', id: '2', title: 'natus commodi et', body: "a", completed: true }, { userId: '1', id: '3', title: 'voluptatem et reprehenderit', body: "c", completed: false }], query = { title: 'l', body: 'a' }, filterData = (data, query) => data.filter(rec => Object.entries(query).every(([k, v]) => rec[k].toString().includes(v)) ); console.log(filterData(data, query));

If you only need the first occurrence just replace filter with find .如果您只需要第一次出现,只需将filter替换为find

const filterData = (data, query) => {
  return data.find(rec => {
    return Object.keys(query)
      .find(key => rec[key] === query[key])
  })
}

Edit: You could combine filter with every like this:编辑:您可以将filterevery结合起来,如下所示:

const filterData = (data, query) => {
  return data.filter((item) => {
    return Object.keys(query).every((key) => {
      return (item[key] + '').includes(query[key] + '');
    }, true);
  });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM