2016-10-20 33 views
3

我有這個數組需要解析成一個有用的對象。每個值的名稱是由/字符分隔的命名空間的集合。之間的每個「/」需要變成一個JS對象屬性的值:使用字符串數組創建一個多級對象,將數組解析爲JS對象

"status": [ 
    { 
    "message": "OK", 
    "name": "/Computer", 
    "values": [] 
    }, 
    { 
    "name": "/Computer/CPU Usage", 
    "values": [] 
    }, 
    { 
    "name": "/Computer/CPU Temp", 
    "values": [] 
    }, 
    { 
    "name": "/Computer/hardware/memory", 
    "values": [] 
    } 
] 

我需要它變成這樣:

"status": { 
    "computer": { 
     "CPU Usage": { 
     "values": [] 
     }, 
     "CPU Temp": { 
     "values": [] 
     }, 
     "hardware": { 
     "memory": { 
      "values": [] 
     } 
     } 
    } 
    } 

到目前爲止,我已經做到了這一點:

var statii = status, // from above.. 
    _parsedStatii = {}; 

for (var i = 0; statii.length < 0; i ++) { 
    var _nameSpaces = statii[i].name.split('/'); 

    // Start at 1 because index 0 is empty (before the first slash) 
    if (!_parsedStatii[_nameSpaces[1]]) { 
     _parsedStatii[_nameSpaces[1]] = {}; 
    } 

    if (!_parsedStatii[_nameSpaces[1]][_nameSpaces[2]]) 
     _parsedStatii[_nameSpaces[1]][_nameSpaces[2]] = {}; 


    if (!_parsedStatii[_nameSpaces[1]][_nameSpaces[2]][_nameSpaces[3]]) 
     _parsedStatii[_nameSpaces[1]][_nameSpaces[2]][_nameSpaces[3]] = {}; 


    if (!_parsedStatii[_nameSpaces[1]][_nameSpaces[2]][_nameSpaces[3]][_nameSpaces[4]]) 
     _parsedStatii[_nameSpaces[1]][_nameSpaces[2]][_nameSpaces[3]][_nameSpaces[4]] = {}; 

} 

很明顯,它沒有接近正確的地方,我嘗試了很多遞歸函數,但是有點遺憾。這個例子給出了我想要實現的最清晰的表示。有任何想法嗎? (請原諒代碼錯別字,它已被釋義)

回答

5

您可以拆分名稱並構建一個對象。

var data = { "status": [{ "message": "OK", "name": "/Computer", "values": [] }, { "name": "/Computer/CPU Usage", "values": [] }, { "name": "/Computer/CPU Temp", "values": [] }, { "name": "/Computer/hardware/memory", "values": [] }] }, 
 
    object = {}; 
 

 
data.status.forEach(function (a) { 
 
    a.name.slice(1).split('/').reduce(function (o, k) { 
 
     return o[k] = o[k] || {}; 
 
    }, object).values = a.values; 
 
}); 
 

 
console.log(object);
.as-console-wrapper { max-height: 100% !important; top: 0; }

+1

Vielen潮溼的龔如心,很好的答案! –