gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 19:37:41 25 4
gpt4 key购买 nike

如何使用 .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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com