atul mishra
atul mishra

Reputation: 299

Changing JSON Structure in Javascript/Jquery

I have an object coming from the server via JSON which is in the below format. I want to rearrange it to another format.

{
    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
    }]
}

I want to change its structure and want this format below:

{
    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
    }
}

Upvotes: 1

Views: 104

Answers (2)

Bartłomiej Gładys
Bartłomiej Gładys

Reputation: 4615

try this:

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

Upvotes: 1

Abdennour TOUMI
Abdennour TOUMI

Reputation: 93163

so use groupBy feature :

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

Then :

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

then map the object 1->week1, .. n->weekn

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

Upvotes: 0

Related Questions