Home > Back-end >  Iterate array of objects without using foreach typescript
Iterate array of objects without using foreach typescript

Time:10-02

Am working on an a array of object.structure given below.

[
    {
        "matListParent": "CH",
        "dParent": "CUST1",
        "isAllSelected": true,
        "childItems": [
            {
                "item": "Display1",
                "isSelected": true
            },
            {
                "item": "Display2",
                "isSelected": false
            }
        ]
    },
  {
        "matListParent": "CH2",
        "dimParent": "CUST2",
        "isAllSelected": true,
        "childItems": [
            {
                "item": "Display5",
                "isSelected": true
            },
            {
                "item": "Display6",
                "isSelected": false
            }
        ]
    }
]

Am trying to get isSelected true item value.i have tried something like this

data.filter(
        (matModel: any) => matModel.matListParent === "CH").map(
          (model: any) => model.childItems).map((item: any) => item).filter((list: any) => list.isSelected);

It return an empty array.

What was the mistake on the above code.

Thanks in advance.

CodePudding user response:

Solution code

data.filter(
        (matModel: any) => matModel.matListParent === "CH").map(
          (model: any) => model.childItems).map((item: any) => item[0]).filter((list: any) => list.isSelected);

Issue explanation

so,

After 1st filter((matModel: any) => matModel.matListParent === "CH") and 1st map((model: any) => model.childItems), we are getting an array of array just like below

[
  [
    { item: 'Display1', isSelected: true },
    { item: 'Display2', isSelected: false }
  ]
]

So when you try to apply a map((item: any) => item) to it again it is giving the same result as above. after that your last filter((list: any) => list.isSelected) will give you nothing.

The above solution will help you and also there are a lot of ways to solve this problem I hope you know how to overcome this problem because now you know where it is going in the wrong direction

  • Related