JS在重命名的顶部转换顶部的深层嵌套物体
我想简化以新属性名称在顶级移动一些嵌套对象。给定此数据:
let data = [
{
"id": 1001,
"model": "Lemon",
"length": "4",
"details": [
{
"id": 38,
"kind": "D",
"color": "Gray",
"specifics": {
"id": 3
}
}
]
},
{
"id": 1002,
"model": "Botanica",
"length": "2",
"details": [
{
"id": 39,
"kind": "A",
"color": "Yellow",
"specifics": {
"id": 1
}
},
{
"id": 40,
"kind": "B",
"color": "Green",
"specifics": {
"id": 2
}
},
]
}
];
我所需的输出:
[
{
"id": 3,
"model": "Lemon",
"color": "Gray",
},
{
"id": 1,
"model": "Botanica",
"color": "Yellow",
},
{
"id": 2,
"model": "Botanica",
"color": "Green",
}
]
结合模型和颜色更好:
[
{
"id": 3,
"model": "Lemon - Gray"
},
{
"id": 1,
"model": "Botanica - Yellow"
},
{
"id": 2,
"model": "Botanica - Green"
}
]
如果有多个细节,它也将与模型和颜色一起创建一个新对象,然后它将在顶部移动。这是我到目前为止尝试的:
const result = data.map(({ details, ...d }) => ({
...d,
data: details.map(({ specifics, ...s }) => ({
...r,
id: specifics.id
}))
}));
但是看来我无法获得正确的结果。如何简化这个?谢谢。
I would like to simplify this nested array of objects move some items at the top level with a new property name. Given this data:
let data = [
{
"id": 1001,
"model": "Lemon",
"length": "4",
"details": [
{
"id": 38,
"kind": "D",
"color": "Gray",
"specifics": {
"id": 3
}
}
]
},
{
"id": 1002,
"model": "Botanica",
"length": "2",
"details": [
{
"id": 39,
"kind": "A",
"color": "Yellow",
"specifics": {
"id": 1
}
},
{
"id": 40,
"kind": "B",
"color": "Green",
"specifics": {
"id": 2
}
},
]
}
];
My desired output:
[
{
"id": 3,
"model": "Lemon",
"color": "Gray",
},
{
"id": 1,
"model": "Botanica",
"color": "Yellow",
},
{
"id": 2,
"model": "Botanica",
"color": "Green",
}
]
Or much better to combine the model and color:
[
{
"id": 3,
"model": "Lemon - Gray"
},
{
"id": 1,
"model": "Botanica - Yellow"
},
{
"id": 2,
"model": "Botanica - Green"
}
]
If there are multiple specifics, it would also create a new object together with the model and color, then it would move at the top. Here's what I've tried so far:
const result = data.map(({ details, ...d }) => ({
...d,
data: details.map(({ specifics, ...s }) => ({
...r,
id: specifics.id
}))
}));
But it seems that I can't get the right result. How to simplify this one? Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,我们需要循环浏览数据阵列。我们可以从数据元素(即
item
)获得model
。然后,我们需要循环浏览该item.details
数组。从中,我们可以获得ID
,lidet.color
。她的是完整的代码。First, we need to loop through the data array. We can get the
model
from the data element namelyitem
. Then we need to loop through thatitem.details
array. From that we can getid
,detail.color
. Hers's the full code.