Saturday 17 July 2021

How to iterate nested object keys with child nested

I want to iterate the nested object keys which will be have inner child nested as well:

Nested object code:

{
    "F2C3C496-BEA6-A5E8-15F0-E2867304B463": {
        "D39FD497-9529-6CC3-70DE-E8D9277C18D3": {
            "child": {
                "87A1817D-CFA9-70FD-131B-224658AF13CE": {
                    "next": {
                        "F7A90266-B7F4-4CC2-0F1B-D4B320E2EC1A": {}
                    }
                }
            },
            "next": {
                "B49927ED-369E-E219-FC1A-8E4BAAFC3933": {
                    "next": {}
                }
            }
        }
    }
}

JS code to iterate:

flowThrough = (obj, callback, context?, path?: string) => {
    let nestedKey=';'
    Object.keys(obj).forEach(key => {
      if(!isEmptyObject(key))
      callback(key, context, path);

      if (!isEmpty(obj[key]) && typeof obj[key] === 'object') {
        if(obj[key].hasOwnProperty('next'))
        nestedKey = obj[key].next;
        else if(obj[key].hasOwnProperty('child'))
        nestedKey = obj[key].child;
        else  nestedKey = obj[key];

        this.flowThrough(nestedKey, callback, context, (path)? has(context, path.concat(".next"))?path.concat(`.next[${get(context, path.concat(".next").length)}]`): path.concat('.').concat("next[0]") : key)
      }
    })
  }

Actually, the above code working for one nested level to get key(ids). If it reaches the empty object key then the loop is ending there. actually, it should check any other child/next is there or not.

Expected output:

{  "flow": [
    {
      "id": "F2C3C496-BEA6-A5E8-15F0-E2867304B463",
      "next": [
        {
          "id": "D39FD497-9529-6CC3-70DE-E8D9277C18D3",
          "child": [
            {
              "id": "87A1817D-CFA9-70FD-131B-224658AF13CE",
              "next": [
                {
                  "id": "F7A90266-B7F4-4CC2-0F1B-D4B320E2EC1A",
                  "next": []
                }
              ]
            }
          ],
          "next": [
            {
              "id": "B49927ED-369E-E219-FC1A-8E4BAAFC3933",
              "next": []
            }
          ]
        }
      ]
    }
  ]
}

Please give me the solution for this.



from How to iterate nested object keys with child nested

No comments:

Post a Comment