[Vuejs]-Deep filter objects in javascript array

-2👍

You could imagine a recursive function which would look something like.

const res = [];
function findMeta(rs) {
  rs.forEach(r => {
      for (let [key, value] of Object.entries(r)) {
        //console.log(`${key}`, value);
                if(key === "children") findMeta(value);
                if(key === "meta") res.push(r);
      }
  })
  return res;
}
const routes = [
    {
        path: "/panel",
        name: "panel",
        redirect: { name: "panel.dashboard" },
        component: {},
        children: [
            {
                path: "/dashboard",
                name: "panel.dashboard",
                component: {},
                meta: {
                    menu: "main"
                },
            },
            {
                path: "/users",
                name: "panel.users",
                redirect: { name: "panel.dashboard" },
                component: {},
                children: [
                    {
                        path: "list",
                        name: "panel.users.list",
                        component: {},
                        meta: {
                            menu: "main"
                        },
                    },
                    {
                        path: "view/:user_id",
                        name: "panel.users.view",
                        component: {},
                    },
                ],
            }
        ],
    }
];

const res = [];
function findMeta(rs) {
  rs.forEach(r => {
      for (let [key, value] of Object.entries(r)) {
        //console.log(`${key}`, value);
				if(key === "children") findMeta(value);
				if(key === "meta") res.push(r);
      }
  })
  return res;
}

console.log(findMeta(routes))

Leave a comment