Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Filter Nested Array To Get Value in ES6

I need to extract listImages that have a status of ‘Existing` inside of an array. My problem is that it gets its parent array.

Data

lists = [
  {
    "listID": "1",
    "listImages": [
      {
        "id": "111",
        "status": "Existing"
      },
      {
        "id": "222",
        "status": "Non-Existing"
      }
    ]
  },
  {
    "listID": "2",
    "listImages": [
      {
        "id": "333",
        "status": "Non-Existing"
      }
    ]
  }
]

Current Code

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const images = lists.map((list) => ({
  ...list,
  listImages: (list.listImages?? []).filter(
    ({ status }) => status === "Existing"
  ),
}));

Expected Output

["111"]

>Solution :

Looks like you just want to get the id. Simply do filter followed by a map for each list. If you want to do this process on all lists and merge the arrays to one, use flatMap.

lists = [
  {
    "listID": "1",
    "listImages": [
      {
        "id": "111",
        "status": "Existing"
      },
      {
        "id": "222",
        "status": "Non-Existing"
      }
    ]
  },
  {
    "listID": "2",
    "listImages": [
      {
        "id": "333",
        "status": "Non-Existing"
      }
    ]
  }
];

const images = lists.flatMap( list => list.listImages.filter(image => image.status === "Existing").map(image => image.id));
console.log(images);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading