Search code examples
javascriptarraysobject

Iterate Nested Object based on each Index


const networkChart = NodeClassification;
  const itemKey = Object.values(networkChart).map((x) => Object.keys(x)[0])
  const itemKey1 = Object.values(networkChart).map((x) => Object.values(x)[0])

  itemKey1.map((item, index) => {
    return (
    item.group = itemKey[index],
    item.Vendor = Object.keys(networkChart)[index]
    )
  })

  // itemKey1.map((item, index) => {
  //   item.group = itemKey[index].toUpperCase()
  // })

  const netArr = itemKey1?.map((data, index) => {
    return {
      "group": data.group,
      "key": data.Vendor,
      "value": data.DownCount
    }
  })

Below "NodeClassification" having nested object in each object having there item objects which I need to break this to form array of object. Result of array of object as shown below to from a structure with new key & existing values. Below attached the bar need to form in this structure on array of object.

JSON Object Structure:
    "NodeClassification": {
             "Mobile": {
                "NORMAL": {
                   "DownCount": 2
                },
                "VIP": {
                   "DownCount": 2
                }
             },
             "MobileRAN": {
                "NORMAL": {
                   "DownCount": 4
                },
                 "VIP": {
                       "DownCount": 4
                    },
                "CRITICAL": {
                       "DownCount": 4
                    }
             }
          }
        
    Result I need based on Array Of Object Structure:
    [{
        group: 'NORMAL',
        key: 'Mobile',
        value: 2
      },
      {
        group: 'VIP',
        key: 'Mobile',
        value: 2
      },
      {
        group: 'NORMAL',
        key: 'MobileRAN',
        value: 4
      },
      {
        group: 'VIP',
        key: 'MobileRAN',
        value: 4
      },
      {
        group: 'CRITICAL',
        key: 'MobileRAN',
        value: 4
      }
    ] 

NodeClassifcation JSON Bar chart


Solution

  • You could get the entries and map the nested entries.

    const
        data = { NodeClassification: { Mobile: { NORMAL: { DownCount: 2 }, VIP: { DownCount: 2 } }, MobileRAN: { NORMAL: { DownCount: 4 }, VIP: { DownCount: 4 }, CRITICAL: { DownCount: 4 } } } },
        result = Object
            .entries(data.NodeClassification)
            .flatMap(([key, o]) => Object
                .entries(o)
                .map(([group, { DownCount: value }]) => ({ group, key, value }))
            );
    
    console.log(result);
    .as-console-wrapper { max-height: 100% !important; top: 0; }