2017-09-02 235 views
-2

我已經嘗試了很多次來對該位置進行分組,但不起作用。希望幫助。謝謝。Javascript將json結構更改爲另一個結構

原JSON:

[ 
{_id: "1", description: "a", location: "us"} 
{_id: "2", description: "b", location: "us"} 
{_id: "3", description: "c", location: "tw"} 
] 

新的JSON:

[ 
{data: [{_id: "1", description: "a"}, {_id: "2", description: "b"}], location: 'us'}, 
{data: [{_id: "3", description: "c"}], location: 'tw'} 
] 
+2

能否請你加你已經嘗試到現在什麼...你可以在這裏回答,但讓我們知道你的嘗試... –

+2

JSON我用於數據交換的*文本符號*。 [(More here。)](http://stackoverflow.com/a/2904181/157247)如果你正在處理JavaScript源代碼,而不是處理*字符串*,那麼你並沒有處理JSON。 (如果*爲*爲JSON,則爲無效;在JSON中,屬性名稱必須用引號引起來。) –

+2

努力解決該問題。 **如果**你被卡住了,告訴我們你試過什麼,告訴我們你有什麼問題,等等。現在這是「寫給我」,這是不適合SO的。 –

回答

1

您可以用做

let arr = [ 
 
{_id: "1", description: "a", location: "us"}, 
 
{_id: "2", description: "b", location: "us"}, 
 
{_id: "3", description: "c", location: "tw"} 
 
]; 
 
let result = [], map = {}, idx = 0; 
 
for(let element of arr){ 
 
    let curr = 0; 
 
    if(map[element.location] !== undefined){ 
 
     curr = map[element.location]; 
 
    } 
 
    else{ 
 
     curr = idx; 
 
     map[element.location] = idx++; 
 
     result.push({data : [], location : element.location}); 
 
    } 
 
    result[curr].data.push({_id: element._id, description: element.description}); 
 

 
} 
 
console.log(result);

0

呦你可以利用哈希表和分組的位置進行優化。

var data = [{ _id: "1", description: "a", location: "us" }, { _id: "2", description: "b", location: "us" }, { _id: "3", description: "c", location: "tw" }], 
 
    locations = Object.create(null), 
 
    result = []; 
 

 
data.forEach(function (o) { 
 
    if (!locations[o.location]) { 
 
     locations[o.location] = { data: [], location: o.location }; 
 
     result.push(locations[o.location]); 
 
    } 
 
    locations[o.location].data.push({ _id: o._id, description: o.description }); 
 
}); 
 

 
console.log(result);

0

功能的方法:

let arr = [ 
    {_id: '1', description: 'a', location: 'us'}, 
    {_id: '2', description: 'b', location: 'us'}, 
    {_id: '3', description: 'c', location: 'tw'} 
] 

let result = Object.entries(arr.reduce((h, {_id, description, location: l}) => 
    Object.assign(h, {[l]: [...(h[l] || []), {_id, description}]}) 
, {})).map(([l, d]) => ({location: l, data: d})) 

console.log(result) 

或者更可讀的辦法:

let arr = [ 
    {_id: '1', description: 'a', location: 'us'}, 
    {_id: '2', description: 'b', location: 'us'}, 
    {_id: '3', description: 'c', location: 'tw'} 
] 

let dict = arr.reduce((dict, {_id, description, location}) => { 
    dict[location] = dict[location] || [] 
    dict[location].push({_id, description}) 
    return dict 
}, {}) 

let result = Object.entries(dict).map(([l, d]) => ({location: l, data: d})) 

console.log(result) 
+0

似乎我的控制檯登錄時它的位置是錯誤的。 例如我可以看到數組(15)在chrome中打開時它實際上包含3個對象 –