Home > Software design >  How to map through an object and return a component based on object keys in react
How to map through an object and return a component based on object keys in react

Time:01-24

I have an objects of object and I want to loop through it and display it based on the key.

Input:

export let data = {
  home: {
    title: "home",
    url: "/home"
  },
  dashboard: {
    title: "dashboard",
    url: "/dashboard"
  },
  pages: {
    title: "pages",
    url: "/pages"
  },
  subpages: {
    title: "subpages",
    url: "/pages/subpages"
  },
  login: {
    title: "login",
    url: "/pages/login"
  },
  account: {
    title: "account",
    url: "/dashboard/account"
  }
}

if URL is a sub url of other object then it should be displayed below it.

Expected output:

Home
dashboard
  account
pages
  subpages
  login

It should be displayed like this but in say <h2> and <p>

CodePudding user response:

You could do this by building up a hierarchy using reduce.

let data = {
  home: {
    title: "home",
    url: "/home"
  },
  dashboard: {
    title: "dashboard",
    url: "/dashboard"
  },
  pages: {
    title: "pages",
    url: "/pages"
  },
  subpages: {
    title: "subpages",
    url: "/pages/subpages"
  },
  login: {
    title: "login",
    url: "/pages/login"
  },
  account: {
    title: "account",
    url: "/dashboard/account"
  }
}

var result = Object.entries(data).reduce((acc,[key,{title,url}]) => {
  const parts = url.substring(1).split("/");
  let obj = acc;
  for(var i=0;i<parts.length;i  ){
    if(!obj[parts[i]]) obj[parts[i]] = {}
    obj = obj[parts[i]];
  }
  obj.url = url;
  return acc;
},{});

console.log(result);

CodePudding user response:

Hey this code snipped can help

let data = {
  home: {
    title: "home",
    url: "/home"
  },
  dashboard: {
    title: "dashboard",
    url: "/dashboard"
  },
  pages: {
    title: "pages",
    url: "/pages"
  },
  subpages: {
    title: "subpages",
    url: "/pages/subpages"
  },
  login: {
    title: "login",
    url: "/pages/login"
  },
  account: {
    title: "account",
    url: "/dashboard/account"
  }
}

Object.entries(data).map(([key, value]) => {
  console.log(key);
})

  • Related