skip to Main Content

I get a JSON data source that looks like this:

[
  {
    "id": 1,
    "name": 'name',
    "array": [
      { "id": 1}, { "id": 2}
    ]
  },
  {...}
]

I’d like to filter this data according to the id contained in the array.

But I don’t know how to do this with array.filter and includes. Can you help me?

2

Answers


  1. You can achieve filtering of the above with the following:

    let data = [
      {
        "id": 1,
        "name": 'name',
        "array": [
          { "id": 1}, { "id": 2}
        ]
      },
    ];
    
    let idToFind = 1; 
    
    let filteredData = data.filter(item => {
      return item.array.some(innerItem => innerItem.id === idToFind);
    });
    
    console.log(filteredData);
    

    filter is used to go through each item in the data array. For each item, the some method is used to check if there is any object in the array field that has an id equal to idToFind. If there is, the item is included in the filteredData array.

    Edit:
    If you want to filter based on multiple ids, you can change the code to:

    let idsToFind = [1, 2]; 
    
    let filteredData = data.filter(item => {
      return item.array.some(innerItem => idsToFind.includes(innerItem.id));
    });
    
    Login or Signup to reply.
  2. It’s very easy to use filter() for your use-case. You just pass an arrow function, whose parameter is named item in this case and which returns (item.id === 1) (or whatever criteria you want to use).

    let myArray = [
      {
        "id": 1,
        "name": 'name',
        "array": [
          { "id": 1}, { "id": 2}
        ]
      },
    ];
    
    console.log(myArray.filter(item => (item.id === 1)));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search