Here's the code.
var temp = [
{
slugs: ['men'],
children: [
{ slugs: ['men', 'tops'], children: [
{ slugs: ['men', 'tops', 'shirts'] },
{ slugs: ['men', 'tops', 'swe'] }
] },
{
slugs: ['men', 'bottoms'], children: [
{ slugs: ['men', 'bottoms', 'pants'] },
{ slugs: ['men', 'bottoms', 'under'] }
]
}
]
},
{
slugs: ['women'],
children: [
{ slugs: ['women', 'tops'], children: [
{ slugs: ['women', 'tops', 'shirts'] },
{ slugs: ['women', 'tops', 'swe'] }
] },
{
slugs: ['women', 'bottoms'], children: [
{ slugs: ['women', 'bottoms', 'pants'] },
{ slugs: ['women', 'bottoms', 'under'] }
]
}
]
}
]
function matchTreeObj (tree, location) {
if (_.isArray(tree) && tree.length > 0) {
for(let i=0;i<tree.length;i++){
matchTreeObj(tree[i], location)
}
}
if (tree.slugs && (tree.slugs.join('/') === location)) {
console.log(tree)
return tree
} else if (tree.children && tree.children.length > 0) {
matchTreeObj(tree.children, location)
}
}
const aaa = matchTreeObj(temp, 'men/tops')
console.log('from log', aaa)
It's using lodash and fiddle is here.
The code basically ouputs the object chunk which its slugs value matches the location parameter.
I could get the console log works properly. But I can not get the returned data. (I already tried to return the function where I use it recursively, and still not work.)
What have I done wrong?