首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何映射2层深的对象

如何映射2层深的对象
EN

Stack Overflow用户
提问于 2018-07-26 03:31:15
回答 1查看 168关注 0票数 -2

我试图映射一个在react中有2层深度的对象,但我似乎无法让它在我的生命中工作。

有人能帮我一把吗?

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

这是对象结构:

EN

回答 1

Stack Overflow用户

发布于 2018-07-26 03:47:34

您需要从第一个map()调用中返回一些内容。如果不这样做,那么映射的结果将只是一个空数组。此外,您似乎没有返回地图的结果,但您可能正计划对其执行其他操作:

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

下面是一个包含简单数据的配对示例:

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

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

https://stackoverflow.com/questions/51526391

复制
相关文章

相似问题

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