简体   繁体   中英

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

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

Expected Output

["111"]

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);

  lists.map(list => list.listImages.filter(image => image.status === 'Existing').map(image => image.id)).flat();

  // output => ['111']

Here you have both imperative and declarative solutions. You can change named functions to arrow functions and make it even a single line but I don't think that we have to follow that ugly coding style where no one (not even future you) understands the code.

 lists = [ { "listID": "1", "listImages": [ { "id": "111", "status": "Existing" }, { "id": "222", "status": "Non-Existing" } ] }, { "listID": "2", "listImages": [ { "id": "333", "status": "Non-Existing" } ] } ] // Imperative solution const images = []; lists.forEach(list => { list.listImages.forEach(image => { if(image.status === 'Existing'){ images.push(image.id); } }) }); console.log(images); // Declarative solution const data = lists.flatMap(function getAllImages(list){ return list.listImages; }).filter(function getExistingImages(image) { return image.status === 'Existing'; }).map(function getIds(image){ return image.id }); console.log(data);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM