首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >遍历数组以获得嵌套对象

遍历数组以获得嵌套对象
EN

Stack Overflow用户
提问于 2018-08-08 16:45:24
回答 1查看 24关注 0票数 0

我试图遍历我的数组,以获得嵌套在其中的特定对象。

有些对象包含children属性,应该遍历该属性,直到找到匹配的对象为止。

下面是一些示例数据,我试图以id作为4来获取对象

代码语言:javascript
复制
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

代码语言:javascript
复制
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';
代码语言:javascript
复制
<div id="foo"></div>

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-08-08 19:28:41

至少有两个问题解释了为什么它不起作用:

  1. return回调中的forEach语句将不将返回的值返回到任何位置。它什么都没发生。
  2. 不检查递归调用的结果。需要对其进行检查,以确定是否定义了它。根据这一点,您可以决定是继续循环还是退出循环。

将该forEach替换为一个for...of循环,这样您就可以返回"out of“,但只有在匹配时才能这样做,否则您需要继续循环:

代码语言:javascript
复制
for (const item of items) {
    const match = getItem(item.children);
    if (match) return match;
}

注意,在代码段中,您不应该将textContent设置为返回值,因为它是一个对象,将被转换为字符串" Object“。例如,您可以获取标题字符串并将其放在textContent中。

代码语言:javascript
复制
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';
代码语言:javascript
复制
<div id="foo"></div>

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51751760

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档