So I've been struggling to wrap my head around this recursive function and get the right results.
const _ = require('lodash');
let config = {
"Main": {
children: {
"Dashboard": "main.dashboard",
"Account": {
children: {
"Settings": "main.account.settings"
}
}
}
},
"Statistics": {
children: {
"Test One": "main.statistics.test.one",
"Test Two": "main.statistics.test.two"
}
}
}
let processNav = (config, parent) => {
let children;
let results = {};
_.forOwn(config, (value, title) => {
var breadcrumb = parent || title;
if (value.children) {
children = processNav(value.children, breadcrumb);
_.assign(results, children);
} else {
results[value] = [breadcrumb, title];
}
});
return results;
};
let breadcrumbs = processNav(config);
console.log(breadcrumbs);
// output
{ 'main.dashboard': [ 'Main', 'Dashboard' ],
'main.account.settings': [ 'Main', 'Settings' ],
'main.statistics.test.two': [ 'Statistics', 'Test Two' ] }
The output I'm looking for is more like this...
// expected output
{ 'main.dashboard': [ 'Main', 'Dashboard' ],
'main.account.settings': [ 'Main', 'Account', 'Settings' ],
'main.statistics.test.one': [ 'Statistics', 'Test One' ],
'main.statistics.test.two': [ 'Statistics', 'Test Two' ] }
Can anyone help me wrap my head around this before I go crazy?
This approach doesn't use .lodash, just plain JS.
let config = { "Main": { children: { "Dashboard": "main.dashboard", "Account": { children: { "Settings": "main.account.settings" } } } }, "Statistics": { children: { "Test One": "main.statistics.test.one", "Test Two": "main.statistics.test.two" } }};
function loop(obj, path, breadcrumbs) {
Object.keys(obj).forEach(k => {
if (obj[k].children) loop(obj[k].children, [...path, k], breadcrumbs);
else breadcrumbs[obj[k]] = [...path, k];
});
}
let breadcrumbs = {};
loop(config, [], breadcrumbs);
console.log(JSON.stringify(breadcrumbs, null, 2));
.as-console-wrapper { max-height: 100% !important; top: 0; }
The main difficulty is skipping the children object. Therefore, I included an additional case in the recursive pattern.
If the current "node" has a children property, it "skips" it by immedeately calling the next recursion:
isParent(obj) ? getPaths(obj.children, path, result) : /* ... * /
In action:
const config={Main:{children:{Dashboard:"main.dashboard",Account:{children:{Settings:"main.account.settings"}}}},Statistics:{children:{"Test One":"main.statistics.test.one","Test Two":"main.statistics.test.two"}}};
const isParent = x => x.children;
const isLeaf = x => typeof x === "string";
const getPaths = (obj, path = [], result = {}) =>
isParent(obj)
// The "Skip" case:
? getPaths(obj.children, path, result)
: isLeaf(obj)
// The *final* case:
? Object.assign(result, { [obj]: path })
// The *recurse* case:
: Object.keys(obj).reduce(
(r, k) => getPaths(obj[k], path.concat(k), r),
result);
console.log(getPaths(config));
Related
Let's assume I have the following array:
[
"About.vue",
"Categories/Index.vue",
"Categories/Demo.vue",
"Categories/Flavors.vue"
]
We use the Index.vue in each sub-folder to act as the parent of that folder. That means the above would look like:
[
{
name: "About",
children: []
},
{
name: "Categories",
children:
[
{
name: "Index.vue",
children: []
},
{
name: "Demo.vue",
children: []
},
{
name: "Flavors.vue",
children: []
}
]
}
]
I was able to get it working slightly by using the following tutorial: https://joelgriffith.net/array-reduce-is-pretty-neat/
However, the thing about that is that it is a root object with a property for each file, as opposed to an array with an object for each file.
The following code produces the intended output:
let paths = [
"About.vue",
"Categories/Index.vue",
"Categories/Demo.vue",
"Categories/Flavors.vue"
];
let helper = {
index: -1,
name: ""
};
function treeify(files) {
var fileTree = [];
function mergePathsIntoFileTree(prevDir, currDir, i, filePath) {
helper.name = currDir;
helper.index = i;
if (helper.index == 0) {
let index = prevDir.findIndex(x => x.name == helper.name);
if (index < 0) {
prevDir.push({
name: helper.name,
children: []
});
}
return prevDir;
}
if (helper.index >= 0) {
let obj = {
name: currDir,
children: []
};
prevDir[helper.index].children.push(obj);
helper.index = i;
helper.name = currDir;
}
}
function parseFilePath(filePath) {
var fileLocation = filePath.split('/');
// If file is in root directory, eg 'index.js'
if (fileLocation.length === 1) {
fileTree[0] = {
name: fileLocation[0],
children: []
};
} else {
fileLocation.reduce(mergePathsIntoFileTree, fileTree);
}
}
files.forEach(parseFilePath);
return fileTree;
}
console.log(treeify(paths));
However, it fails on the following input:
let paths = [
"About.vue",
"Categories/Index.vue",
"Categories/Demo.vue",
"Categories/Flavors.vue",
"Categories/Types/Index.vue",
"Categories/Types/Other.vue"
];
Does anyone know a solution to get it working for further nested lists of paths?
You can create this structure using forEach method to loop each path and split it to array on /, then you can also use reduce method to create nested objects.
let paths = ["About.vue","Categories/Index.vue","Categories/Demo.vue","Categories/Flavors.vue","Categories/Types/Index.vue","Categories/Types/Other.vue"];
let result = [];
let level = {result};
paths.forEach(path => {
path.split('/').reduce((r, name, i, a) => {
if(!r[name]) {
r[name] = {result: []};
r.result.push({name, children: r[name].result})
}
return r[name];
}, level)
})
console.log(result)
So, first off, I am going to assume this is in Node.js, second, I am currently at home so I don't have access to node.js at the moment so I had no real way of testing the code, however the following code should work.
What you need to do is check the contents of the folder and then make a check to see if an item in the folder is a directory or not, if true, call the function again with the new path (a.k.a. recursion).
So first you start by reading the folder, add each item's name to the .name property of the object, then you check if it's a folder or not, if it is, recursive for that path. Keep returning an array of objects back (this will be added to the .children property.
var fs = require('fs');
var filetree = DirToObjectArray('path/to/folder/');
function DirToObjectArray(path) {
var arr = [];
var content = fs.readdirSync(path, { withFileTypes: true });
for (var i=0; i< content.length; i++) {
var obj = new Object({
name: "",
children: []
});
obj.name = content[i].name;
if (content[i].isDirectory()) {
obj.children = DirToObjectArray(path + content[i].name + "/");
}
arr.push(obj);
}
return arr;
}
If you are not using node.js but in-browser javascript, I can't help you with that
You could take an iterative approach for every found name part and get an object and return the children for the next search.
var paths = ["About.vue", "Categories/Index.vue", "Categories/Demo.vue", "Categories/Flavors.vue", "Categories/Types/Index.vue", "Categories/Types/Other.vue"],
result = paths.reduce((r, p) => {
var names = p.split('/');
names.reduce((q, name) => {
var temp = q.find(o => o.name === name);
if (!temp) q.push(temp = { name, children: [] });
return temp.children;
}, r);
return r;
}, []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
I went with #Nenad Vracar's answer (and upvoted, thank you!), but I also had the need to allow duplicate filenames in my use case. I just wanted to share how I did that.
let paths = ["About.vue","Categories/Index.vue","Categories/Demo.vue","Categories/Flavors.vue","Categories/Types/Index.vue","Categories/Types/Other.vue","Categories/Types/Other.vue","Categories/Types/Other.vue"];
let result = [];
let level = {result};
paths.forEach(path => {
path.split('/').reduce((r, name, i, a) => {
if(!r[name]) {
r[name] = {result: []};
r.result.push({name, children: r[name].result});
} else if (i === a.length - 1) {
// Allow duplicate filenames.
// Filenames should always be at the end of the array.
r.result.push({name, children: []});
}
return r[name];
}, level)
})
console.log(result)
The following solution was derived from #nenad-vracar's answer. One shortcoming with his answer is that if a path contains "result", the code will fail. A simple workaround would be to rename "result" to "", that is, include characters that cannot appear in a path.
export interface IPathNode {
name: string;
children: IPathNode[];
path: IPath | null;
}
export interface IPath {
key: string;
directory: boolean;
}
interface IPathLevel {
// ["<result>"]: IPathNode[];
[key: string]: IPathLevel | IPathNode[];
}
export const createPathTree = (paths: IPath[]): IPathNode | null => {
const level: IPathLevel = { ["<result>"]: [] as IPathNode[] };
paths.forEach((path) => {
path.key.split("/").reduce(
((
currentLevel: IPathLevel,
name: string,
index: number,
array: string[]
) => {
if (!currentLevel[name]) {
currentLevel[name] = { ["<result>"]: [] };
(currentLevel["<result>"] as IPathNode[]).push({
name,
children: (currentLevel[name] as IPathLevel)[
"<result>"
] as IPathNode[],
/* Attach the path object to the leaf node. */
path: index === array.length - 1 ? path : null,
});
}
return currentLevel[name];
}) as any,
level
);
});
const finalArray = level["<result>"] as IPathNode[];
return finalArray.length > 0 ? finalArray[0] : null;
};
console.log(
JSON.stringify(
createPathTree([
{
key: "/components/button.tsx",
directory: false,
},
{
key: "/components/checkbox.tsx",
directory: false,
},
{
key: "/result",
directory: true,
},
]),
null,
4
)
);
Output:
{
"name": "",
"children": [
{
"name": "components",
"children": [
{
"name": "button.tsx",
"children": [],
"path": {
"key": "/components/button.tsx",
"directory": false
}
},
{
"name": "checkbox.tsx",
"children": [],
"path": {
"key": "/components/checkbox.tsx",
"directory": false
}
}
],
"path": null
},
{
"name": "result",
"children": [],
"path": {
"key": "/result",
"directory": true
}
}
],
"path": null
}
I want to get my file directories as nested array object but i can't seem to figure out how to convert
[
'routes/files',
'routes/files/emptyfolder',
'routes/files/somefolder',
'routes/files/somefolder/example.docx',
'routes/files/test.docx',
'routes/randomdata.json'
]
to
[
{
title: 'routes',
content: [
{
title: 'files',
content: [
{
title: 'empty folder',
content: []
},
{
title: 'somefolder',
content: [
{
title: 'example.docx',
},
]
},
{
title: 'test.docx',
}
],
},
{
title: 'randomdata.json'
}
],
}
]
it looks impossible problem for me to solve.
I would love to know how to solve it.
Thank you.
Here is how I solved it:
Not the best solution, but works.
const arr = [
"routes/files",
"routes/files/emptyfolder",
"routes/files/somefolder",
"routes/files/somefolder/example.docx",
"routes/files/test.docx",
"routes/randomdata.json",
];
const arr2 = arr.map((p) => p.split("/"));
const setNestedObjectField = (
obj,
props,
value
) => {
if (!Array.isArray(obj)) {
if (!obj.content) {
obj.content = [];
}
obj = obj.content;
}
for (const propName of props) {
const next = obj.find((el) => el.title === propName);
if (!next) {
console.assert(props.at(-1) === propName);
// last propName
obj.push(value);
} else {
if (!next.content) {
next.content = [];
}
obj = next.content;
}
}
};
const rez = [];
let index = 0;
while (arr2.some((s) => s[index] !== undefined)) {
// arr2 = arr2.filter((a) => a.length);
const layer = arr2.reduce((acc, pathArr) => {
if (pathArr[index] === undefined) return acc;
acc.add(pathArr.slice(0, index + 1).join("/"));
return acc;
}, new Set());
// console.log({ layer });
for (const key of layer) {
setNestedObjectField(rez, key.split("/"), { title: key.split("/").at(-1) });
}
index++;
}
console.log(rez);
I came across this question and it's an interesting problem, I know it's already been answered, but I wanted to spend a little of my time to solve it my way.
here I leave my code:
function nestedDirectories (arr) {
const splittedArray = arr.map(a => a.split('/'));
return {
mergeObjs: function(target, source) {
for (let key in source) {
if(!target[key]) target[key] = {};
target[key] = this.mergeObjs(target[key], source[key]);
}
return target;
},
buildResponse: function (objMain) {
let arr = [];
for (let key in objMain) {
let o = { title: key, content: [] };
if(key.includes(".")) {
delete o.content;
} else if (Object.keys(objMain[key]).length) {
o.content = this.buildResponse(objMain[key]);
}
arr.push(o);
}
return arr;
},
exec: function () {
let targetObject = {};
splittedArray.forEach(arrParent => {
let strObj = '';
for (let i = arrParent.length - 1; i >= 0 ; i--) {
strObj = `"${arrParent[i]}": {${strObj}}`;
}
let parseObj = JSON.parse(`{${strObj}}`);
targetObject = this.mergeObjs(targetObject, parseObj);
});
return this.buildResponse(targetObject);
}
}
}
and use it like this:
const dirs = [
'routes/files',
'routes/files/emptyfolder',
'routes/files/somefolder',
'routes/files/test.docx',
'routes/randomdata.json',
'routes/files/somefolder/example.docx'
];
const data = nestedDirectories(dirs).exec();
result:
[
{
title: 'routes',
content: [
{
title: 'files',
content: [
{ title: 'emptyfolder', content: [] },
{
title: 'somefolder',
content: [ { title: 'example.docx' } ]
},
{ title: 'test.docx' }
]
},
{ title: 'randomdata.json' }
]
}
]
I have an array of objects, where each object has a property (parentsList) indicating the category the current item belongs to, something like:
const data = [
{
...other properties,
"parentsList": [
"Assets",
"Icons"
],
},
{
...other properties,
"parentsList": [
"Assets",
"Fonts"
],
},
{
...other properties,
"parentsList": [
"Programming",
"JavaScript",
"Docs"
],
},
{
...other properties,
"parentsList": [
"Programming",
"JavaScript",
"React",
"Libraries",
],
},
]
That means the first object belongs to assets/icons, the second to assets/fonts, third to programming/javascript/docs and so on.
I'm trying to map it to a tree-like view, where siblings should be under the same parent, something like:
const data = [
{
name: 'Assets',
id: 'assets',
children: [
{
name: 'Icons',
id: 'assets/icons',
},
{
name: 'Illustrations',
id: 'assets/illustrations',
},
],
},
{
name: 'Programming',
id: 'programming',
children: [
{
name: 'JavaScript',
id: 'programming/javascript',
children: [
{
name: 'Docs',
id: 'programming/javascript/docs',
},
{
name: 'React',
id: 'programming/javascript/react',
children: [
{
name: 'Libraries',
id: 'programming/javascript/react/libraries',
},
],
},
],
},
],
},
]
I imagine it's gonna be easier to traverse from the right, maybe with reduceRight(), but I can't seem to get it right.
Anyone would know how to achieve that?
Thanks!
I tend to avoid using reduce because I find it difficult to read the code that has reduce in it. So, here is a non-reduce way.
const data = [
{
parentsList: [
"Assets",
"Icons"
],
},
{
parentsList: [
"Assets",
"Fonts"
],
},
{
parentsList: [
"Programming",
"JavaScript",
"Docs"
],
},
{
parentsList: [
"Programming",
"JavaScript",
"React",
"Libraries",
],
},
];
const processedData = [];
for (const item of data) {
const parents = [...item.parentsList].reverse();
let children = processedData;
const ids = [];
while (parents.length > 0) {
const parent = parents.pop();
ids.push(parent.toLowerCase());
let foundParent = false;
for (const child of children) {
if (child.name === parent) {
children = child.children;
foundParent = true;
break;
}
}
if (!foundParent) {
const newChild = {name: parent, id: ids.join("/"), children: [],};
children.push(newChild);
children = newChild.children;
}
}
}
console.log(processedData);
You can do this as a combination of forEach and reduce and create a nested hierarchy based on the parentsList array.
const data = [{"parentsList":["Assets","Icons"]},{"parentsList":["Assets","Fonts"]},{"parentsList":["Programming","JavaScript","Docs"]},{"parentsList":["Programming","JavaScript","React","Libraries"]}]
const result = []
data.forEach(function({ parentsList, ...rest }) {
let id = '';
parentsList.reduce((r, name, i) => {
id += (id.length ? '/' : '') + name.toLowerCase();
if (!r[name]) {
const value = { id, name }
r[name] = {result: []}
if (i != parentsList.length - 1) {
value.children = r[name].result
} else {
Object.assign(value, rest)
}
r.result.push(value)
}
return r[name]
}, this)
}, {result})
console.log(result)
A short approach by using nested objects as hash tables.
const
data = [{ parentsList: ["Assets", "Icons"] }, { parentsList: ["Assets", "Fonts"] }, { parentsList: ["Programming", "JavaScript", "Docs"] }, { parentsList: ["Programming", "JavaScript", "React", "Libraries"] }],
tree = data.reduce((t, { parentsList }) => {
parentsList.reduce((r, name, i, a) => {
const id = a.slice(0, i + 1).join('/').toLowerCase();
if (!r[name]) {
r[name] = { _: { name, id } };
(r._.children ??= []).push(r[name]._);
}
return r[name];
}, t);
return t;
}, { _: {} })._.children;
console.log(tree);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Let's assume I have the following array:
[
"About.vue",
"Categories/Index.vue",
"Categories/Demo.vue",
"Categories/Flavors.vue"
]
We use the Index.vue in each sub-folder to act as the parent of that folder. That means the above would look like:
[
{
name: "About",
children: []
},
{
name: "Categories",
children:
[
{
name: "Index.vue",
children: []
},
{
name: "Demo.vue",
children: []
},
{
name: "Flavors.vue",
children: []
}
]
}
]
I was able to get it working slightly by using the following tutorial: https://joelgriffith.net/array-reduce-is-pretty-neat/
However, the thing about that is that it is a root object with a property for each file, as opposed to an array with an object for each file.
The following code produces the intended output:
let paths = [
"About.vue",
"Categories/Index.vue",
"Categories/Demo.vue",
"Categories/Flavors.vue"
];
let helper = {
index: -1,
name: ""
};
function treeify(files) {
var fileTree = [];
function mergePathsIntoFileTree(prevDir, currDir, i, filePath) {
helper.name = currDir;
helper.index = i;
if (helper.index == 0) {
let index = prevDir.findIndex(x => x.name == helper.name);
if (index < 0) {
prevDir.push({
name: helper.name,
children: []
});
}
return prevDir;
}
if (helper.index >= 0) {
let obj = {
name: currDir,
children: []
};
prevDir[helper.index].children.push(obj);
helper.index = i;
helper.name = currDir;
}
}
function parseFilePath(filePath) {
var fileLocation = filePath.split('/');
// If file is in root directory, eg 'index.js'
if (fileLocation.length === 1) {
fileTree[0] = {
name: fileLocation[0],
children: []
};
} else {
fileLocation.reduce(mergePathsIntoFileTree, fileTree);
}
}
files.forEach(parseFilePath);
return fileTree;
}
console.log(treeify(paths));
However, it fails on the following input:
let paths = [
"About.vue",
"Categories/Index.vue",
"Categories/Demo.vue",
"Categories/Flavors.vue",
"Categories/Types/Index.vue",
"Categories/Types/Other.vue"
];
Does anyone know a solution to get it working for further nested lists of paths?
You can create this structure using forEach method to loop each path and split it to array on /, then you can also use reduce method to create nested objects.
let paths = ["About.vue","Categories/Index.vue","Categories/Demo.vue","Categories/Flavors.vue","Categories/Types/Index.vue","Categories/Types/Other.vue"];
let result = [];
let level = {result};
paths.forEach(path => {
path.split('/').reduce((r, name, i, a) => {
if(!r[name]) {
r[name] = {result: []};
r.result.push({name, children: r[name].result})
}
return r[name];
}, level)
})
console.log(result)
So, first off, I am going to assume this is in Node.js, second, I am currently at home so I don't have access to node.js at the moment so I had no real way of testing the code, however the following code should work.
What you need to do is check the contents of the folder and then make a check to see if an item in the folder is a directory or not, if true, call the function again with the new path (a.k.a. recursion).
So first you start by reading the folder, add each item's name to the .name property of the object, then you check if it's a folder or not, if it is, recursive for that path. Keep returning an array of objects back (this will be added to the .children property.
var fs = require('fs');
var filetree = DirToObjectArray('path/to/folder/');
function DirToObjectArray(path) {
var arr = [];
var content = fs.readdirSync(path, { withFileTypes: true });
for (var i=0; i< content.length; i++) {
var obj = new Object({
name: "",
children: []
});
obj.name = content[i].name;
if (content[i].isDirectory()) {
obj.children = DirToObjectArray(path + content[i].name + "/");
}
arr.push(obj);
}
return arr;
}
If you are not using node.js but in-browser javascript, I can't help you with that
You could take an iterative approach for every found name part and get an object and return the children for the next search.
var paths = ["About.vue", "Categories/Index.vue", "Categories/Demo.vue", "Categories/Flavors.vue", "Categories/Types/Index.vue", "Categories/Types/Other.vue"],
result = paths.reduce((r, p) => {
var names = p.split('/');
names.reduce((q, name) => {
var temp = q.find(o => o.name === name);
if (!temp) q.push(temp = { name, children: [] });
return temp.children;
}, r);
return r;
}, []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
I went with #Nenad Vracar's answer (and upvoted, thank you!), but I also had the need to allow duplicate filenames in my use case. I just wanted to share how I did that.
let paths = ["About.vue","Categories/Index.vue","Categories/Demo.vue","Categories/Flavors.vue","Categories/Types/Index.vue","Categories/Types/Other.vue","Categories/Types/Other.vue","Categories/Types/Other.vue"];
let result = [];
let level = {result};
paths.forEach(path => {
path.split('/').reduce((r, name, i, a) => {
if(!r[name]) {
r[name] = {result: []};
r.result.push({name, children: r[name].result});
} else if (i === a.length - 1) {
// Allow duplicate filenames.
// Filenames should always be at the end of the array.
r.result.push({name, children: []});
}
return r[name];
}, level)
})
console.log(result)
The following solution was derived from #nenad-vracar's answer. One shortcoming with his answer is that if a path contains "result", the code will fail. A simple workaround would be to rename "result" to "", that is, include characters that cannot appear in a path.
export interface IPathNode {
name: string;
children: IPathNode[];
path: IPath | null;
}
export interface IPath {
key: string;
directory: boolean;
}
interface IPathLevel {
// ["<result>"]: IPathNode[];
[key: string]: IPathLevel | IPathNode[];
}
export const createPathTree = (paths: IPath[]): IPathNode | null => {
const level: IPathLevel = { ["<result>"]: [] as IPathNode[] };
paths.forEach((path) => {
path.key.split("/").reduce(
((
currentLevel: IPathLevel,
name: string,
index: number,
array: string[]
) => {
if (!currentLevel[name]) {
currentLevel[name] = { ["<result>"]: [] };
(currentLevel["<result>"] as IPathNode[]).push({
name,
children: (currentLevel[name] as IPathLevel)[
"<result>"
] as IPathNode[],
/* Attach the path object to the leaf node. */
path: index === array.length - 1 ? path : null,
});
}
return currentLevel[name];
}) as any,
level
);
});
const finalArray = level["<result>"] as IPathNode[];
return finalArray.length > 0 ? finalArray[0] : null;
};
console.log(
JSON.stringify(
createPathTree([
{
key: "/components/button.tsx",
directory: false,
},
{
key: "/components/checkbox.tsx",
directory: false,
},
{
key: "/result",
directory: true,
},
]),
null,
4
)
);
Output:
{
"name": "",
"children": [
{
"name": "components",
"children": [
{
"name": "button.tsx",
"children": [],
"path": {
"key": "/components/button.tsx",
"directory": false
}
},
{
"name": "checkbox.tsx",
"children": [],
"path": {
"key": "/components/checkbox.tsx",
"directory": false
}
}
],
"path": null
},
{
"name": "result",
"children": [],
"path": {
"key": "/result",
"directory": true
}
}
],
"path": null
}
My answer is inspired from #Nenad Vracar. But unlike his solution where he used for each and reduce which I think unnecessary.
let final = {result:[]};
for (const path of paths) {
let context = final;
for (const name of path.split('/')) {
if (!context[name]) {
context[name] = {result:[]};
context.result.push({name, children: context[name].result});
}
context = context[name];
}
}
console.log(final.result)
I try to write a function in JavaScript which filter an array by a selected property (an value).
But it works for 2 level only I do not understand what do I missing.
The data I want to filter:
var data = [
{
name: "john_pc",
children: [
{
name: "sabrina_pc",
children: [
{
name: "sabrina_pc"
},
{
name: "john_pc"
}
]
},
{
name: "john_pc"
}
]
},
{
name: "sabrina_pc"
}
]
The childrenFilter funciton :
const childrenFilter = (childrenData, filters) => {
let filteredData = childrenData.filter(item => {
for (var property in filters) {
var optionalValues = filters[property];
var value = item[property];
if (item.children) {
item.children = childrenFilter(item.children, filters);
}
let hasValue = value == optionalValues;
if (hasValue) {
return true;
}
return false;
}
return false;
}, this);
return filteredData;
}
Calling the function:
As you can see the 'childrenFilter' get an object which the key is property in the data and the key is value I want to keep.
let result = childrenFilter(data, {
"name": "a1"
});
console.log(JSON.stringify(result, null, 2))
The wanted result :
[
{
"name": "john_pc",
"children": [
{
"name": "sabrina_pc",
"children": [
{
"name": "john_pc"
}
]
},
{
"name": "john_pc"
}
]
}
]
Your filter function does not take into account whether or not children elements match the pattern, therefore even though some child elements of the object match the pattern, the object itself is being filtered out.
Here is the explanation:
{
name: "a2", // does not match filter {name:'a1} so is removed alongside child objects
children: [ // gets removed with parent object
{
name: "a2"
},
{
name: "a1"
}
]
}
This should produce the desired output:
const childrenFilter = (childrenData, filters) => {
let filteredData = childrenData.filter(item => {
for (var property in filters) {
var optionalValues = filters[property];
var value = item[property];
if (item.children) {
item.children = childrenFilter(item.children, filters);
}
let hasValue = value == optionalValues;
if (hasValue || item.children.length) { // include item when children mathes the pattern
return true;
}
return false;
}
return false;
}, this);
return filteredData;
}
You could build new array for each step of filtering, beginning from the leaves and check if this contains the wanted value.
This approach generates new objects and does not mutate the original data.
function filter(array, filters) {
return array.reduce((r, o) => {
var children = filter(o.children || [], filters);
return children || Object.entries(filters).every(([k, v]) => o[k] === v)
? (r || []).concat(Object.assign({}, o, children && { children }))
: r;
}, undefined);
}
var data = [{ name: "a1", children: [{ name: "a2", children: [{ name: "a2" }, { name: "a1" }] }, { name: "a1" }] }, { name: "b1" }];
console.log(filter(data, { name: "a1" }));
.as-console-wrapper { max-height: 100% !important; top: 0; }