var data = [{
id: 1,
name: '家电',
goods: [{
id: 11,
gname: '冰箱',
goods: [{
id: 111,
gname: '海尔'
}, {
id: 112,
gname: '美的'
},
]
}, {
id: 12,
gname: '洗衣机'
}]
}, {
id: 2,
name: '服饰'
}];
function getID(data, id) {
var o={};
data.some(function (item) {
if (item.id == id) {
o=item;
return true;
} else if (item.goods && item.goods.length > 0) {
o = getID(item.goods, id);
}
})
return o;
}
console.log(getID(data,111));
使用some函数,便于退出循环