在Javascript / Jquery中更改JSON结构

时间:2016-09-10 14:36:45

标签: javascript jquery json

我有一个来自服务器的对象,通过JSON,格式如下。我想将其重新排列为另一种格式。

{
    visits: [{
        week: 1,
        count: 3
    }, {
        week: 2,
        count: 3
    }, {
        week: 3,
        count: 4
    }, {
        week: 4,
        count: 3
    }, {
        week: 5,
        count: 1
    }],
    visitors: [{
        week: 1,
        count: 3
    }, {
        week: 2,
        count: 3
    }, {
        week: 3,
        count: 4
    }, {
        week: 4,
        count: 3
    }, {
        week: 5,
        count: 1
    }]
}

我想更改其结构,并希望使用以下格式:

{
    week1: {
        visits: 3
        visitors: 1
    }
    week2: {
        visits: 3
        visitors: 3
    }
    week3: {
        visits: 4
        visitors: 4
    }
    week4: {
        visits: 3
        visitors: 3
    }
    week5: {
        visits: 4
        visitors: 4
    }
}

2 个答案:

答案 0 :(得分:1)

试试这个:

var newObj = {}

$.each(a.visits, function(key,obj){ newObj['week'+obj.week] ={visits: obj.count} });

$.each(a.visitors, function(key,obj){ newObj['week'+obj.week].visitors = obj.count});

答案 1 :(得分:0)

所以使用groupBy功能:

var groupBy=function(jsonArray,key) {
      return jsonArray.reduce(function(rv, x) {
        (rv[x[key]] = rv[x[key]] || []).push(x);
        return rv;
      }, {});
   };

然后:

var groupedByWeeks=groupBy(yourJsonArray.visits,'week')

然后映射对象1->week1,.. n->weekn

Object.keys(groupedByWeeks).map((k)=>
     groupedByWeeks['week'+k]=groupedByWeeks[k];
)