【问题标题】:How to map through an object 2 levels deep如何通过 2 层深的对象进行映射
【发布时间】:2018-07-25 19:31:15
【问题描述】:

我正在尝试映射一个反应深度为 2 级的对象,但我似乎无法让它为我的生活工作。

谁能帮我一把?

 loadBeers() {
    const { userData } = this.props;
    if (userData.location) {
        Object.keys(userData.location).map(locationitem => {
            Object.keys(userData.location[locationitem].beer).map(beerItem => {
                return (
                    <BeerItem key={beerItem}>{userData.location[locationitem].beer[beerItem].beerName}</BeerItem>
                );
            });
        });
    } else {
        return 'hi';
    }
}

这是对象结构:

【问题讨论】:

  • 对象结构是什么?举个例子会更清楚。
  • 如果您添加对象可能会有所帮助,这样人们就不必猜测了。
  • 我现在已经添加了,对不起。

标签: javascript reactjs


【解决方案1】:

您需要从您的第一个 map() 呼叫中返回一些内容。如果您不这样做,该地图的结果将只是一个空数组。此外,您似乎没有返回地图的结果,但也许您正计划用它做其他事情:

loadBeers() {
    const { userData } = this.props;
    if (userData.location) {
       // also return result to original caller of loadBeers()
       return Object.keys(userData.location).map(locationitem => {
            /* Return something here from map callback */
            return Object.keys(userData.location[locationitem].beer).map(beerItem => {
                return (
                    <BeerItem key={beerItem}>{userData.location[locationitem].beer[beerItem].beerName}</BeerItem>
                );
            });
        });
    } else {
        return 'hi';
    }
}

这是一个带有简单数据的配对示例:

let userData = {location :{randoKey: {beer: {anotherweridKey:{ABV: 'some_abv',beerName: 'Bud',beerType: 'bad'}}}}}


let matrix
if (userData.location) {
  matrix = Object.keys(userData.location).map(locationitem => {
    return Object.keys(userData.location[locationitem].beer).map(beerItem => {
      return userData.location[locationitem].beer[beerItem].beerName
    });
  });
} else {
  console.log('hi');
}

console.log(matrix)

【讨论】:

  • 很好,马克,我完全忘记了 return
猜你喜欢
  • 2022-07-25
  • 1970-01-01
  • 2023-01-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-02
  • 2023-02-08
相关资源
最近更新 更多