在 JavaScript 中根据另一个数组过滤一个对象数组

filter an array of objects based on another array in javascript

提问人:Kareem Sleem 提问时间:11/13/2023 最后编辑:Kareem Sleem 更新时间:11/13/2023 访问量:45

问:

我有一个对象数组,我想用另一个数组过滤它,所以在这个例子中,我希望结果是 id 为 3 的对象

//the array of objects
const array = [
  {
    id: 1,
    Country: "x",
    industry: "technology",
  },
  {
    id: 2,
    Country: "y",
    industry: "Data alaysis",
  },
  {
    id: 3,
    Country: "y",
    industry: "technology",
  },
];

//the filters array
const filters = ["technology", "y"];

我试图检查这两个键在对象数组中的值是否与这样的过滤器数组匹配

  const keys = [
    "industry",
    "Country"
  ];

  const search = (array) => {
    return array.filter(
      (item) =>
        keys.some((key) => item[key].includes(filters))
    );
  };

但它仅在数组中有一个值时才有效,所以我希望它检查数组中的所有值

JavaScript ReactJS 数组 过滤器

评论

0赞 Roko C. Buljan 11/13/2023
问题是 的顺序是否总是与 的索引完全匹配?你没有考虑到这个重要的方面。const filters = ["technology", "y"];const keys = ["industry","Country"];

答:

0赞 berkobienb 11/13/2023 #1

尝试这样的事情:

const array = [
  {
    id: 1,
    Country: "x",
    industry: "technology",
  },
  {
    id: 2,
    Country: "y",
    industry: "Data analysis",
  },
  {
    id: 3,
    Country: "y",
    industry: "technology",
  },
];

const filters = ["technology", "y"];

const keys = ["industry", "Country"];

const search = (array) => {
  return array.filter((item) =>
    keys.some(key => filters.includes(item[key]))
  );
};

console.log(search(array));