我想正确返回儿童对象。我该怎么做?


function Ha8(arr, id) {
let result = [];
for(let i = 0;  i < arr.length; i++) {
if(Array.isArray(arr[i].children)) {
// if it is a array, it going to be run recursive
result.push(arr[i].children)
const col = Ha8(result[i], id);
if(col === id)  {
// find it in array in array 
return result
// then return the id object, 
} else {
continue; // still can't find.. go ahead! 
}  
} else if (arr[i]['id']===id) {
return arr[i] // will return valid id object 
}
return null // if its none , return null, or parameter id is undefined. 
}
}

I m write意向方向。但这行不通……我该如何修复?请给我一些小费。

let input = [
{
id: 1,
name: 'johnny',
},
{
id: 2,
name: 'ingi',
children: [
{
id: 3,
name: 'johnson',
},
{
id: 5,
name: 'steve',
children: [
{
id: 6,
name: 'lisa',
},
],
},
{
id: 11,
},
],
},
{
id: '13',
},
];
output = Ha8(input, 5);
console.log(output); // --> { id: 5, name: 'steve', children: [{ id: 6, name: 'lisa' }] }
output = Ha8(input, 99);
console.log(output); // --> null

我想这样返回,但只返回'null' ..需要使用递归检查子对象的id并返回子对象。我这样写。但是我不知道……如何正确返回子id的元素?

我将用一种完全不同的方法给你一个答案,并使用JSON.stringify()方法的魔力,更具体地说是replacer可选参数,它允许使用回调函数,可以用作过滤器。

可以看到,它大大简化了最终代码。还可以对它进行修改,不仅引入id,还引入任何键或值,就像我在最后一种方法中所做的那样。

编辑:按照您的建议,由于您希望您的函数是递归的,我建议您使用Array.reduce()方法。它允许对所有属性进行优雅的迭代,直到需求得到满足。

使用null作为初始值,这是reduce方法的最后一个参数,它允许以以下方式迭代数组中的所有字段:

  • 第一个if总是在第一次迭代时被跳过,因为初始值为null。

  • 第二个if将设置currentValue为累加器,如果属性id存在并且等于您试图查找的值

  • 第三个if,您可以添加Array.isArray()来添加类型验证,将检查属性children是否存在。因为它是最后一个,所以只有在所有其他条件都不满足的情况下才会起作用。如果此属性存在,它将再次调用Ha8Recursive以重新启动进程。

  • 最后,如果这两个都不工作,它应该返回null。如果没有最后一个条件,如果输入id不存在,则返回undefined

const Ha8 = (array, inputKey, inputValue) => {
let children = null;
JSON.stringify(array, (key, value) => {
if (value[inputKey] && value[inputKey] === inputValue) {
children = value;
}
return value;
});
return children;
};
const Ha8Recursive = (array, inputKey, inputValue) => {
return array.reduce((accumulator, currentValue) => {
if (accumulator) {
return accumulator;
} else if (currentValue[inputKey] && currentValue[inputKey] === inputValue) {
return currentValue;
} else if (currentValue.children) {
return Ha8Recursive(currentValue.children, inputKey, inputValue);
} else {
return null;
}
}, null)
}
const input = [{"id":1,"name":"johnny"},{"id":2,"name":"ingi","children":[{"id":3,"name":"johnson"},{"id":5,"name":"steve","children":[{"id":6,"name":"lisa"}]},{"id":11}]},{"id":"13"}];
console.log('JSON stringify function');
console.log(Ha8(input, 'id', 5));
console.log('Recursive function')
console.log(Ha8Recursive(input, 'id', 5));

相关内容

最新更新