Javascript将json结构更改为另一个结构

时间:2017-09-02 07:37:46

标签: javascript arrays json

我已多次尝试对该位置进行分组但不起作用。希望有所帮助感谢。

原json:

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

new json:

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

3 个答案:

答案 0 :(得分:0)

你可以使用

来做

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);

答案 1 :(得分: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); 

答案 2 :(得分: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)