2017-09-02 236 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个对象 –