过滤嵌套数组的对象值

时间:2021-05-06 12:30:37

标签: javascript arrays filter

我有一个对象数组

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 data = Object.values(parsed).filter(({ type,path }) => type === "file");

喜欢

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

2 个答案:

答案 0 :(得分:1)

您可以使用 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);

通过对象解构,你可以让它更紧凑

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

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

答案 1 :(得分:1)

使用这种方式,您可以在数组中任意深入并过滤任何级别的元素,

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