javascript - 在 React 组件的多次嵌套对象上使用 ES6 .map()

标签 javascript reactjs object ecmascript-6 array.prototype.map

如何使用 .map() 迭代此对象:

state = { 
      contacts: [
        { "id":1,
           "name":"Leanne Graham",
           "email":"<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4112282f2224332401203133282d6f23283b" rel="noreferrer noopener nofollow">[email protected]</a>",
           "address":{
              "street":"Kulas Light",
              "city":"Gwenborough",
              "geo":{
                 "lat":"-37.3159",
                 "lng":"81.1496"
              }
           },
           "phone":"1-770-736-8031",
        },
        { "id":2,
           "name":"Ervin Howell",
           "email":"<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2c7f444d42424d6c414940455f5f4d02585a" rel="noreferrer noopener nofollow">[email protected]</a>",
           "address":{
              "street":"Victor Plains",
              "city":"Wisokyburgh",
              "geo":{
                 "lat":"-43.9509",
                 "lng":"-34.4618"
              }
           },
           "phone":"010-692-6593",
        }
     ]
    }

因此联系人 map 将起作用,因为它是一个数组,并且所有数据(如 ID、姓名、电子邮件和电话)都可以访问,但如果我想迭代地址,则会崩溃。我使用了一些例子,例如:

render(){
  const {contacts} = this.state
  return(
    <>
       {Object.keys(contacts.address).map((address, index) => (
          <span className="d-block" key={index}>{contacts.address[address]}</span>
        ))}
    </>
  );
}

它应该适用于地址,但在 geo{} 上崩溃,此时我失去了信号。

有人可以给我一个想法吗?

最佳答案

这应该有帮助:

const address = contacts[0].address;

<>
  {Object.keys().map((addressKey, index) => (
    <span className="d-block" key={index}>
      {typeof address[addressKey] === "object"
        ? Object.keys(address[addressKey]).map(e => (
            <span>{address[addressKey][e]}</span>
          ))
        : contacts[0].address[address]}
    </span>
  ))}
</>;

关于javascript - 在 React 组件的多次嵌套对象上使用 ES6 .map(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60812020/

相关文章:

javascript - 如何中止 http 拦截器中的请求?

javascript - Bootstrap 4 选项卡不切换

reactjs - 有没有办法热构建 React 来与 Django 一起使用?

javascript - 尝试避免在没有回调 hell 的快速路由中使用匿名函数

javascript - 将样式应用于特定的 v-for 元素

javascript - 如何使用 React refs 来聚焦 Redux 表单字段?

reactjs - 如果子组件的 props 保持不变,为什么 React 会重新渲染它?

javascript - 如何用 reactjs 修复 "Expected to return a value in arrow function"?

javascript - 在javascript中从对象数组中删除一个对象

Ruby:从对象数组中的一个值创建新数组