我有一个对象数组
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“的对象的路径。
我现在所做的是没有给出一个适当的结果:
const data = Object.values(parsed).filter(({ type,path }) => type === "file");喜欢
const resultedData = ["storage/inventory/inventory.yaml","storage/ui/config.js","storage/ui/gulpfile.js"]发布于 2021-05-06 20:37:44
您可以使用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),
],
[]
);发布于 2021-05-06 20:53:48
使用这种方法,您可以在数组中深入任意深度,并在任何级别过滤元素,
data.map((element) => {
return {...element, subElements: element.subElements.filter((subElement) => subElement.type === "file")}
});https://stackoverflow.com/questions/67418185
复制相似问题