let find = (array, id) => {
let stack = [];
let going = true;
let walker = (array, id) => {
array.forEach(item => {
if (!going) return;
stack.push(item['id']);
if (item['id'] === id) {
going = false;
} else if (item['items']) {
walker(item['items'], id);
} else {
stack.pop();
}
});
if (going) stack.pop();
}
walker(array, id);
return stack;
}
let list = [
{
id: 1,
value:11,
items: [
{
id: 2,
value: 21,
items: [
{
id: 3,
value: 31,
}
]
}
]
},
{
id: 4,
value: 41
}
]
console.log(find(list, 3))
function serachAttrByAttr(data,attr,attrValue,targetAttr,childAttr){
let result = null
let fn = function(data,attr,attrValue,targetAttr,childAttr){
data.forEach((item)=>{
if(item[attr] === attrValue){
result = item[targetAttr]
} else if( Array.isArray(item[childAttr]) && item[childAttr].length > 0){
fn(item[childAttr],attr,attrValue,targetAttr,childAttr)
}
})
}
fn(data,attr,attrValue,targetAttr,childAttr)
console.log(result)
return result
}
serachAttrByAttr(list,'id',4,'value','items')
console