<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
let obj = [
{
id:1,
name:'家电',
goods:[
{
id:11,
name:'冰箱',
},
{
id:12,
name:'洗衣机',
goods:[
{
id:121,
name:'海尔冰箱'
}
]
}
]
},
{
id:2,
name:'服饰'
}
]
function getById(json,id){
var o = {}
json.forEach((item) => {
if(item.id == id){
o = item
}else if(item.goods && item.goods.length > 0){
o = getById(item.goods,id)
}
})
return o;
}
console.log(getById(obj,1));
console.log(getById(obj,2));
console.log(getById(obj,121));
console.log(getById(obj,12));
</script>
</body>
</html>
递归遍历数据
最新推荐文章于 2022-09-17 15:41:29 发布