1

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
    }
}
2
  • What have you tried? Any code to share? Commented Sep 10, 2016 at 14:42
  • That's not JSON, and even if you get the data as JSON, it's irrelevant for the problem. Commented Sep 10, 2016 at 14:50

2 Answers 2

1

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});
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.