根据其值过滤JavaScript表

时间:2019-03-23 23:14:26

标签: javascript arrays sorting

我的表/数组是用Javascript创建的,不是用HTML硬编码的。

我正在尝试根据访问过英国的任何人来过滤并返回表格。

我想放置一个带有(候选人,国家/地区)参数的函数。

var people = [
      { name: "Matt", countries: ["UK", "USA", "Russia"] },
      { name: "Simon", countries: ["Canada", "China"] },
      { name: "Ben", countries: ["UK", "India"] },
      { name: "Katie", countries: ["UK", "China"] },
      { name: "Omar", countries: ["Canada", "China"] },
      { name: "Simon", countries: ["India", "China", "USA"] },
    ];

我尝试过

people.filter(person=>person.countries.includes('UK'))

但是,如果我使用此代码,则该表不是动态的,并且不会更改以反映在我的网页上,而是仅返回“ people”的原始数组。为什么这种方法行不通?

1 个答案:

答案 0 :(得分:0)

我认为这是您要寻找的东西

const people = [
  { name: "Matt", countries: ["UK", "USA", "Russia"] },
  { name: "Simon", countries: ["Canada", "China"] },
  { name: "Ben", countries: ["UK", "India"] },
  { name: "Katie", countries: ["UK", "China"] },
  { name: "Omar", countries: ["Canada", "China"] },
  { name: "Simon", countries: ["India", "China", "USA"] },
];

const filterCandidates = (candidates, country) =>
  candidates.filter(({ countries }) =>  countries.includes(country));

结果:

  

[{“ name”:“ Matt”,“ countries”:[“ UK”,“ USA”,“ Russia”]}​​,{“ name”:“ Ben”,“ countries”:[“ UK”, “ India”]}​​,{“ name”:“ Katie”,“ countries”:[“ UK”,“ China”]}]

https://es6console.com/jtm4kvvn/