【问题标题】:map array inside nested array嵌套数组内的映射数组
【发布时间】:2021-05-27 13:33:50
【问题描述】:

我有一个数组,其中包含另一个需要映射的嵌套数组。我想我几乎得到了它,但我没有取回该数据,只能看到它的一个对象。查看新索引,我可以看到它正在循环对象数组中的对象数量。

这是我目前拥有的:

class Menu extends Component {
    constructor(props) {
        super(props);
        const arrayItems = [this.props.items.edges]
        arrayItems.map((currentItem, index) => {
            console.log("The current iteration is: " + index)
            console.log("The current item is: " + currentItem)
            return currentItem.map((newCurrentItem, newIndex) => {
                console.log("The NEW current iteration is: " + newIndex)
                console.log("The NEW current item is: " + newCurrentItem)
                return newCurrentItem
            })
        })

...
}

这是我在控制台中看到的屏幕截图,看起来很有希望:

有人可以指点我正确的方向吗?

【问题讨论】:

  • 输入是什么?你想要的输出是什么?
  • 我认为您正在迭代一个对象数组。如果是这样,则无法使用 map 迭代对象
  • @eux 我想在状态中使用它们之前按字母顺序对数据进行排序,所以这是我在状态中使用它们之前尝试实现的步骤。请参阅我的另一篇文章了解更多详情:stackoverflow.com/questions/66272670/…。我的问题是是否可以像我目前正在尝试做的那样映射对象。这是 miraj answer 派上用场的地方。你能解释一下吗?我将如何从 newCurrentItem 中获取数据?

标签: javascript arrays reactjs


【解决方案1】:

在我看到您使用sort items in state alphabetically 的命令后,我相信映射节点值应该是您想要的。

  const newCurrentItem = [{ node: "abc" }, { node: "def" }];

  // [Object, Object]
  console.log(newCurrentItem);

  // ["abc", "def"]
  console.log(
    newCurrentItem.map((data) => {
      return data.node;
    })
  );

  const newCurrentItem2 = [{ node: { aaa: "bbb" } }, { node: { aaa: "yyy" } }];

  // [Object, Object]
  console.log(newCurrentItem2);

  // ["bbb", "yyy"]
  console.log(
    newCurrentItem2.map((data) => {
      return data.node.aaa;
    })
  );

Code sand box

【讨论】:

    【解决方案2】:

    实际上,currentItem 在您的代码中等于 this.props.items.edges,因此您可以映射 this.props.items.edges

    newCurrentItem 显示为[object Object] 是因为What does [object Object] mean? (JavaScript)

    所以您可以照常从CurrentItem 中获取数据。

    您的代码可以简化为:

    class Menu extends Component {
        constructor(props) {
            super(props);
            const arrayItems = this.props.items.edges
            return arrayItems.map((currentItem) => {
                return currentItem.id // or other attributes you what
            })
    
    ...
    }
    

    【讨论】:

      【解决方案3】:

      试试arrayItems.forEach(currentItem => { //do something }) 您也可以使用.map,在这种情况下,您需要像@eux 所说的那样提取任何属性的值

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-09-25
        • 2019-08-13
        • 2013-03-21
        • 1970-01-01
        • 1970-01-01
        • 2016-04-10
        • 2013-08-08
        • 2013-07-17
        相关资源
        最近更新 更多