简体   繁体   中英

Filtering object values of the nested array

I have an array of objects

const data = [
  {
    id: 1,
    name: "Inventory",
    type: "directory",
    path: "storage/inventory/",
    children: [
      {
        id: 2,
        name: "inventory.yaml",
        type: "file",
        path: "storage/inventory/inventory.yaml",
      },
    ],
  },
  {
    id: 3,
    name: "UI",
    type: "directory",
    path: "storage/ui/",
    children: [
      {
        id: 10,
        name: "config.js",
        type: "file",
        path: "storage/ui/config.js",
      },
      {
        id: 13,
        name: "gulpfile.js",
        type: "file",
        path: "storage/ui/gulpfile.js",
      },
    ],
  },
];

My purpose is to get an array which will include only pathes of the objects which type is "file".

What I am doing now is not giving a proper result:

const data = Object.values(parsed).filter(({ type,path }) => type === "file");

Like

const resultedData = ["storage/inventory/inventory.yaml","storage/ui/config.js","storage/ui/gulpfile.js"]

You can achieve this using reduce

 const data = [{ id: 1, name: "Inventory", type: "directory", path: "storage/inventory/", children: [{ id: 2, name: "inventory.yaml", type: "file", path: "storage/inventory/inventory.yaml", }, ], }, { id: 3, name: "UI", type: "directory", path: "storage/ui/", children: [{ id: 10, name: "config.js", type: "file", path: "storage/ui/config.js", }, { id: 13, name: "gulpfile.js", type: "file", path: "storage/ui/gulpfile.js", }, ], }, ]; const result = data.reduce((acc, curr) => { const { children } = curr; const paths = children.filter((o) => o.type === "file").map((o) => o.path); return [...acc, ...paths]; }, []); console.log(result);

with Object destructuring you can make it more compact

const result = data.reduce((acc, { children }) => {
  const paths = children.filter((o) => o.type === "file").map((o) => o.path);
  return [...acc, ...paths];
}, []);

or

const result = data.reduce(
  (acc, { children }) => [
    ...acc,
    ...children.filter((o) => o.type === "file").map((o) => o.path),
  ],
  []
);

Using this way you can go as deep as you want in an array and filter elements at any level,

data.map((element) => {
  return {...element, subElements: element.subElements.filter((subElement) => subElement.type === "file")}
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM