我一直在try 将嵌套对象转换为另一个树对象,但没有成功.我想不出它的解决方案,所以任何帮助都将不胜感激.
Expected output
[
{
"duration": 2117538,
"duration_min": 1001,
"duration_max": 201530,
"input": 0,
"output": 0,
"label": "down",
"id": "0",
"children": [
{
"duration": 211538,
"duration_min": 1001,
"duration_max": 201530,
"input": 0,
"output": 0,
"boxes": 0,
"label": "other",
"id": "0-1",
"children": [
{
"duration": 1538,
"duration_min": 1001,
"duration_max": 201530,
"input": 0,
"output": 0,
"boxes": 0,
"id": "0-1-0",
"label": "no resource",
},
]
}
]
}
]
如您所见,对象的子对象被放入子对象中,随后添加了id字段.
让我们看看输入格式及其 struct .在data
对象中,有键down
及其值,这是一个对象.在这个物体里面有values
和other
. keys 不是values
,而是放在 children 身上.
Given input
const data = {
"down": {
"values": {
"duration": 2117538,
"duration_min": 1001,
"duration_max": 201530,
"input": 0,
"output": 0,
"boxes": 0,
},
"other": {
"no resource": {
"values": {
"duration": 1538,
"duration_min": 1001,
"duration_max": 201530,
"input": 0,
"output": 0,
"boxes": 0,
}
},
"values": {
"duration": 211538,
"duration_min": 1001,
"duration_max": 201530,
"input": 0,
"output": 0,
"boxes": 0,
}
}
}
}
What I tried
function getTransformData(object, name = 'total') {
return Object.entries(object).map(function ([key, value]) {
if (key === 'values') {
return { ...value, label: name };
}
if (value.values) {
return { ...value.values, label: key, children: getTransformData(value, key) };
}
});
}
console.log(getTransformData(data))
但这并不能满足需要.