如何在深2级的物体上进行映射

时间:2018-07-25 19:31:15

标签: javascript reactjs

我试图映射一个反应深度为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';
    }
}

这是对象结构:

the object structure as seen when logged in the browser

1 个答案:

答案 0 :(得分: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)