我一直在嘗試將嵌套物件轉換為另一個樹物件,但沒有成功。我無法弄清楚它的解決方案,所以任何幫助將不勝感激。
預期產出
[
{
"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 欄位。在下面的示例中,我們有一個由valueskey 及其子項組成的物件,即other. 在內心深處,有no resource一個只有valueskey 的 key,這意味著不會有 children 陣列。
讓我們看看輸入格式及其結構。在data物件中,有鍵down和它的值,它是一個物件。在那個物件里面有values和other。不是的鑰匙,values被放入兒童中。
給定輸入
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,
}
}
}
}
我試過的
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))
但這不能按需要作業。
uj5u.com熱心網友回復:
問題已解決。
function transformNestedObject({values,...children}, id, duration) {
duration = duration || values.duration;
children = Object.entries(children).map(([key, value],i)=>{
const _id = id ? id "-" i : '' i;
const durationPercent = (value.values.duration / duration * 100.0).toFixed(2) '%';
return {
id: _id,
label: key,
durationPercent,
...transformNestedObject( value, _id, duration)
}
});
if (id) {
return {...values, children};
}
return children;
}
console.log(transformNestedObject(data));
uj5u.com熱心網友回復:
使用遞回:
function to_tree(d, c = []){
var r = {false:[], true:[]}
var vals = []
var k = 0;
for (var i of Object.keys(d)){
r[i === 'values'].push(d[i])
}
for (var i of r[true]){
vals.push({...i, 'id':[...c, k].map(x => x.toString()).join('-')});
k ;
}
for (var i of r[false]){
if (vals.length){
vals[vals.length-1]['children'] = to_tree(i, [...c, k])
}
else{
vals = [...vals, ...to_tree(i, c)]
}
}
return vals
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/455832.html
標籤:javascript 目的 树 转型
上一篇:我試圖訪問JSON代碼中的陣列/物件元素?我試過了,但沒有正確顯示
下一篇:HowcanIselectitemfromdropdown,whenoption'selementnotinteractableviaselenium/python?
