Ian
Ian

Reputation: 87

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"]

Upvotes: 0

Views: 138

Answers (2)

RGA
RGA

Reputation: 313

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")}
});

Upvotes: 1

DecPK
DecPK

Reputation: 25401

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),
  ],
  []
);

Upvotes: 1

Related Questions