简体   繁体   中英

map array inside nested array

I have an array with another nested array I need to map over. I think I almost got it but I am not getting that data back, can only see its an object. Looking at the new index I can see it is looping of the amount of objects in the object array.

Here is what I have currently:

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
            })
        })

...
}

Here is screenshot of what I can see in my console, which looks promising:

在此处输入图像描述

Can someone please point me in correct direction?

Actually, currentItem is equal to this.props.items.edges in your code, so you could just map this.props.items.edges .

newCurrentItem display as [object Object] is because What does [object Object] mean? (JavaScript) .

So you could get data out of CurrentItem as normal.

Your code could be simplified to:

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
        })

...
}

After I've seen your command with sort items in state alphabetically , I believe map the node value should be what you want.

  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

try arrayItems.forEach(currentItem => { //do something }) You can use .map too bt in that case you need to extract the value of any property like @eux said

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM