[英]i wanna return correctly children's object. how can i?
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.
}
}
我寫了預期的方向。 但它不起作用..我該如何解決? 請給我一些提示。
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並使用遞歸返回孩子的object。 所以我就這樣寫。 但我不知道..如何正確返回兒童 id 的元素?
我將使用完全不同的方法給你一個答案,並使用JSON.stringify()
方法的魔力,更具體地說是replacer
可選參數,它允許使用可用作過濾器的回調 function。
如您所見,它大大簡化了最終代碼。 它也可以被修改為不僅引入一個 id,還引入任何鍵或值,就像我在最終方法中所做的那樣。
編輯:根據您的建議,由於您更喜歡 function 是遞歸的,我建議您使用Array.reduce()
方法。 它允許對所有屬性進行優雅的迭代,直到滿足需求。
使用null
作為初始值,這是reduce
方法的最后一個參數,它允許通過以下方式遍歷數組中的所有字段:
第一個 if 在第一次迭代時總是會被跳過,因為初始值為 null。
如果屬性 id 存在並且等於您嘗試查找的值,則第二個 if 會將 currentValue 設置為累加器
第三個 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));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.