首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >过滤嵌套数组的对象值

过滤嵌套数组的对象值
EN

Stack Overflow用户
提问于 2021-05-06 20:30:37
回答 2查看 37关注 0票数 0

我有一个对象数组

代码语言:javascript
复制
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",
      },
    ],
  },
];

我的目的是得到一个数组,它将只包含类型为"file“的对象的路径。

我现在所做的是没有给出一个适当的结果:

代码语言:javascript
复制
const data = Object.values(parsed).filter(({ type,path }) => type === "file");

喜欢

代码语言:javascript
复制
const resultedData = ["storage/inventory/inventory.yaml","storage/ui/config.js","storage/ui/gulpfile.js"]
EN

回答 2

Stack Overflow用户

发布于 2021-05-06 20:37:44

您可以使用reduce实现这一点

代码语言:javascript
复制
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);

使用对象解构可以使其更紧凑

代码语言:javascript
复制
const result = data.reduce((acc, { children }) => {
  const paths = children.filter((o) => o.type === "file").map((o) => o.path);
  return [...acc, ...paths];
}, []);

代码语言:javascript
复制
const result = data.reduce(
  (acc, { children }) => [
    ...acc,
    ...children.filter((o) => o.type === "file").map((o) => o.path),
  ],
  []
);
票数 1
EN

Stack Overflow用户

发布于 2021-05-06 20:53:48

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

代码语言:javascript
复制
data.map((element) => {
  return {...element, subElements: element.subElements.filter((subElement) => subElement.type === "file")}
});
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67418185

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档