0
Follow
0
View

Filter json by key in Javascript [duplicate]

dutefei 注册会员
2023-01-24 19:44

I hope following example code will give you some idea..

I used JsonPlaceholder Mock API https://jsonplaceholder.typicode.

Above mentioned API giving data ouput is:

[
  {
    "userId": 1,
    "id": 1,
    "title": "delectus aut autem",
    "completed": false
  },
  {
    "userId": 1,
    "id": 2,
    "title": "quis ut nam facilis et officia qui",
    "completed": false
  },
  {
    "userId": 1,
    "id": 3,
    "title": "fugiat veniam minus",
    "completed": false
  },
  [...]

I have to separate following selected result from above mentioned API, (It's Id is 187):

{
  completed: false,
  id: 187,
  title: "consequuntur animi possimus",
  userId: 10
}

For that I have used following JS code:

var  targetID = 187; // need to filter with following ID

fetch('https://jsonplaceholder.typicode.com/todos/')
  .then(response => response.json())
  .then((data) => {
    const result = data.filter(function (el) {
      return el.id == targetID; // Changed the matching value
    });
    console.log('FIltered Value', result);
});

Working Fiddle https://jsfiddle.net/katheer_mizal/9jdh5wuy/1/

More Details:

Js parse and filter a json

Find object by id in an array of JavaScript objects

About the Author

Question Info

Publish Time
2023-01-24 19:44
Update Time
2023-01-24 19:44