2016-10-03 30 views
0

我有以下格式數據..壓扁JSON使得一個屬性是鍵和其他值

var array = [{"name":"abc","boss":"def","sub":[{"schema":"a","data":1},{"schema":"b","data":0},{"schema":"c","data":0}]}, 
. 
. 
. 
] 

我希望將其轉變爲以下結構:

[{"name":"abc","boss":"def","a":1,"b":0,"c":0}, 
    . 
    . 
    . 
    ] 

基於該回答here ..我想..

grouped = []; 
array.forEach(function (a) { 
    if (!this[a.name]||!this[a.boss]) { 
     this[a.name] = { name: a.name, boss:a.boss }; 
     grouped.push(this[a.name]); 
     } 
    this[a.name][a.sub.schema] = (this[a.name][a.sub.schema] || 0) + a.sub.data; 
}, Object.create(null)); 

console.log(grouped); 

以上給出了不確定的:如NaN的在R的第三個屬性成立對象..

任何幫助真誠讚賞。

感謝

+0

'a.sub'是一個數組。你將不得不遍歷它 – Rajesh

回答

2

你可能想在sub對象reduce到該項目的屬性。

下面的代碼在array項映射到一個新的數組,其中包含扁平物品:

array = array.map(function(item) { 
    item = item.sub.reduce(function(x,y) { return x[y.schema] = y.data, x; }, item); 
    delete item.sub; 
    return item; 
}); 
+0

喜歡使用__'Comma運算符'___ – Rayon

2

簡單地嘗試此。

var arr = []; 
array.forEach(function(ele){ 
    var obj = {};obj.name=ele.name; 
    obj.boss=ele.boss; 
    ele.sub.forEach(function(e){ 
    obj[e.schema] = e.data 
    }); 
    arr.push(obj) 
}); 
相關問題