0

I have this json data

{
  "default": [
    [
      1325876000000,
      0
    ],
    [
      1325876000000,
      0
    ],
    [
      1325876000000,
      0
    ],
    [
      1325876000000,
      0
    ]
  ],
  "direct": [
    [
      1328196800000,
      0
    ],
    [
      1328196800000,
      100
    ],
    [
      1328196800000,
      0
    ],
    [
      1328196800000,
      0
    ]
  ],
  "Sales": [
    [
      1330517600000,
      0
    ],
    [
      1330517600000,
      0
    ],
    [
      1330517600000,
      91
    ],
    [
      1330517600000,
      0
    ]
  ],
  "Support": [
    [
      1332838400000,
      0
    ],
    [
      1332838400000,
      0
    ],
    [
      1332838400000,
      0
    ],
    [
      1332838400000,
      0
    ]
  ]
}

and I want to change it to this format:

data = [{
           label: 'defaul',
           data: the array here
       }, {
           label: 'name',
           data: the array here
       }, {
           label: 'name',
           data: the array here
       }, {
           label: 'name',
           data: the array here
       }];

In the past, I was doing this:

var thearray = result.default.
var theOtherArray = result.direct

...
..
and so on

It was working because I already know the name of the labels. I mean the label's name were static.

but now they are dynamic so I can't know the name of the lable.

what should I do please?

Edit

I know that I have to use

   var data = [];
    $.each(result, function (index, value) {
    var obj = {};
    obj.label = SOMETHING
    obj.data = result[label]
    data.push(obj);
}

but how to get the SOMETHING

2
  • basically you need every element to be jsonObject which is wrapped inside a jsonArray... so you can write a method to return a jsonObject which will be added to global jsonArray... Commented Apr 15, 2014 at 8:41
  • @vivek this is the data that I have, I can't change its format Commented Apr 15, 2014 at 8:42

1 Answer 1

7

Map the object into an array

var data = $.map(result, function(arr,key) {
    return {label: key, data: arr};
});

FIDDLE

Sign up to request clarification or add additional context in comments.

3 Comments

is data the output variable , an array
@MarcoDinatsoli - yes, it's exactly what you asked for.
I'd rather upvote an answer that uses Vanilla JS, but a) Array.prototype.map is only available for IE9+ (a for loop wouldn't be that bad) and b) the question does mention jQuery, so... good one.

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.