Home > front end >  Nested array of object data display on UI
Nested array of object data display on UI

Time:11-23

I have following response from backend as an array of object,

const cloudData = [
  {
    dataCenter: "AWS-East",
    availablechannels: [
      {
        channelName: "E-channel1",
        id: 1,
      },
      {
        channelName: "E-channel2",
        id: 2,
      },
      {
        channelName: "E-channel3",
        id: 3,
      },
    ],
  },
  {
    dataCenter: "AWS-West",
    availablechannels: [
      {
        channelName: "W-channel1",
        id: 1,
      },
      {
        channelName: "W-channel2",
        id: 2,
      },
      {
        channelName: "W-channel3",
        id: 3,
      },
    ],
  },
];

I need to display on UI grid in following way ,

AWS East
E-channel1
E-channel2
E-channel3

I have tried using es6 map and filter

CodePudding user response:

Using Array#reduce and Array#map:

const data = [
  {
    dataCenter: "AWS-East",
    availablechannels: [
      { channelName: "E-channel1", id: 1 },
      { channelName: "E-channel2", id: 2 },
      { channelName: "E-channel3", id: 3 }
    ]
  },
  {
    dataCenter: "AWS-West",
    availablechannels: [
      { channelName: "W-channel1", id: 1 },
      { channelName: "W-channel2", id: 2 },
      { channelName: "W-channel3", id: 3 }
    ]
  }
];

const res = data.reduce((list, { dataCenter, availablechannels = [] }) => ([
  ...list,
  dataCenter,
  ...availablechannels.map(({ channelName }) => channelName)
]), []);

console.log(res);

CodePudding user response:

You can do this :

cloudData.forEach((datacenter)=> {
    console.log(datacenter.dataCenter)
    datacenter.availablechannels.forEach((channel)=>{
    console.log(channel.channelName)
       })
    })
  • Related