根据其值过滤javascript表

问题描述 投票:-2回答:1

我的表/数组是用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'))

但是,如果我使用此代码,表格不是动态的,并且不会更改以在我的网页上反映这一点,而只是返回“人员”的原始数组。为什么这种方法不起作用?

javascript arrays sorting
1个回答
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”: “马特”, “国家”: “英国”, “USA”, “俄罗斯”]},{ “名”: “奔”, “国家”: “英国”, “印度” ]},{ “名”: “凯蒂”, “国家”: “英国”, “中国”]}]

https://es6console.com/jtm4kvvn/

© www.soinside.com 2019 - 2024. All rights reserved.