我试图遍历我的数组,以获得嵌套在其中的特定对象。
有些对象包含children属性,应该遍历该属性,直到找到匹配的对象为止。
下面是一些示例数据,我试图以id作为4来获取对象
const items = [{
id: 1,
title: 'Title for Item 1'
},
{
id: 2,
title: 'Title for Item 2',
children: [
{
id: 3,
title: "Title for Item 3",
children: [
{
id: 4,
title: "Title for Item 4",
}
]
}
]
},
]我编写了一些遍历代码,但它返回undefined。
const items = [{
id: 1,
title: 'Title for Item 1'
},
{
id: 2,
title: 'Title for Item 2',
children: [
{
id: 3,
title: "Title for Item 3",
children: [
{
id: 4,
title: "Title for Item 4",
}
]
}
]
},
]
const getItem = (items) => {
if (!items) return;
const item = items && items.find(i => i.id === 4);
if (!item) {
items.forEach(i => {
return getItem(i.children)
})
// This is where undefined is returned
} else {
console.log({
item
}) // Prints the correct object.
return item;
}
};
const s = getItem(items); // undefined
document.querySelector('#foo').textContent = s ? s : 'undefined';<div id="foo"></div>
发布于 2018-08-08 19:28:41
至少有两个问题解释了为什么它不起作用:
return回调中的forEach语句将不将返回的值返回到任何位置。它什么都没发生。将该forEach替换为一个for...of循环,这样您就可以返回"out of“,但只有在匹配时才能这样做,否则您需要继续循环:
for (const item of items) {
const match = getItem(item.children);
if (match) return match;
}注意,在代码段中,您不应该将textContent设置为返回值,因为它是一个对象,将被转换为字符串" Object“。例如,您可以获取标题字符串并将其放在textContent中。
const items = [{
id: 1,
title: 'Title for Item 1'
},
{
id: 2,
title: 'Title for Item 2',
children: [
{
id: 3,
title: "Title for Item 3",
children: [
{
id: 4,
title: "Title for Item 4",
}
]
}
]
},
]
const getItem = (items) => {
if (!items) return;
const item = items && items.find(i => i.id === 4);
if (!item) {
for (const item of items) {
const match = getItem(item.children);
if (match) return match;
}
} else {
console.log({
item
}) // Prints the correct object.
return item;
}
};
const s = getItem(items); // undefined
document.querySelector('#foo').textContent = s ? s.title : 'undefined';<div id="foo"></div>
https://stackoverflow.com/questions/51751760
复制相似问题