Anirudh
Anirudh

Reputation: 3358

how to get objects from a JSON array based on a key value pair inside the object in typescript without looping

Below is my JSON Array. I need to get the objects from the array which have objects with key:name and value:cricket.

Is there any way I can achieve this without using loops?

[
  {
 "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"
  }

]

Upvotes: 0

Views: 831

Answers (1)

distante
distante

Reputation: 7005

Using 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

Upvotes: 1

Related Questions