[英]How to loop nested object from props in React?
I am trying to build an obj model from these props:我正在尝试从这些道具构建一个 obj model:
cars.data: {
details: [
{
id: Audi,
attributes: [
{id: audi1, value: 1},
{id: audi2, value: 2},
{id: audi3, value: 3}
]
},
{
id: BMW,
attributes: [
{id: bmw1, value: 1},
{id: bmw2, value: 2},
{id: bmw3, value: 3}
]
},
{
id: Merc,
attributes: [
{id: merc1, value: 1},
{id: merc2, value: 2},
{id: merc3, value: 3}
]
},
]
}
I am having difficulty mapping over the attributes array, how is the right way to map this nested array properly?我在映射属性数组时遇到困难,map 这个嵌套数组的正确方法是什么? This is my attempt:
这是我的尝试:
const objModel = {
details: [
props.cars.data.details.map(item => (
{
id: item.id,
attributes: [
item.map(item => (
{
id: item.attributes.id,
value: item.attributes.value
}
))
]
}
))
]
}
Specifically it's this part that is not working (I think because it's a map within a map):具体来说,这部分不起作用(我认为因为它是地图中的 map):
item.map(item => (
{
id: item.attributes.id,
value: item.attributes.value
}
))
What is the right way to loop the attributes to get each id and value循环属性以获取每个 id 和 value 的正确方法是什么
It should be item.attributes.map
eg它应该是
item.attributes.map
例如
attributes: item.attributes.map(attr => (
{
id: attr.id,
value: attr.value
}
)
const data = { details: [ { id: 'Audi', attributes: [ { id: 'audi1', value: 1 }, { id: 'audi2', value: 2 }, { id: 'audi3', value: 3 }, ], }, { id: 'BMW', attributes: [ { id: 'bmw1', value: 1 }, { id: 'bmw2', value: 2 }, { id: 'bmw3', value: 3 }, ], }, { id: 'Merc', attributes: [ { id: 'merc1', value: 1 }, { id: 'merc2', value: 2 }, { id: 'merc3', value: 3 }, ], }, ], } const objModel = { details: data.details.map(item => ({ id: item.id, attributes: item.attributes.map(attr => ({ id: attr.id, value: attr.value, })), })), } console.log(objModel)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.