[英]Filtering object values of the nested array
我有一个对象数组
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"]
您可以使用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);
通过 Object 解构,您可以使其更紧凑
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),
],
[]
);
使用这种方式,您可以 go 在数组中任意深度,并在任何级别过滤元素,
data.map((element) => {
return {...element, subElements: element.subElements.filter((subElement) => subElement.type === "file")}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.