如何在TypeScript中基于对象内的键值对从JSON数组获取对象而不循环

时间:2019-03-01 11:31:52

标签: json typescript

下面是我的JSON数组。我需要从数组中获取具有key:name和value:cricket对象的对象。

有没有不用循环就可以实现这一目标的方法?

[
  {
 "name": "cricket",
 "ground": "JBL Ground",
 "capacity": "50000"
  },
{
 "name": "rugby",
 "ground": "IPL Ground",
 "capacity": "55000"
  },
{
 "name": "running",
 "ground": "PPL Ground",
 "capacity": "10000"
  },
{
 "name": "cricket",
 "ground": "MBL Ground",
 "capacity": "34000"
  },
{
 "name": "cricket",
 "ground": "KIG Ground",
 "capacity": "19000"
  }

]

1 个答案:

答案 0 :(得分:1)

使用Array.filter

const allData = [
  {
 "name": "cricket",
 "ground": "JBL Ground",
 "capacity": "50000"
  },
{
 "name": "rugby",
 "ground": "IPL Ground",
 "capacity": "55000"
  },
{
 "name": "running",
 "ground": "PPL Ground",
 "capacity": "10000"
  },
{
 "name": "cricket",
 "ground": "MBL Ground",
 "capacity": "34000"
  },
{
 "name": "cricket",
 "ground": "KIG Ground",
 "capacity": "19000"
  }

]

const wantedData = allData.filter(item => item.name === 'cricket');

console.log(wantedData);

Example