0

I have a JSON like this:

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

I want to generate array contains the name of each item and the first value of the corresponing array. the result should be like this:

ticks = [["default", 1325876000000],["direct", 1328196800000],["Sales", 1330517600000],["Support", 1332838400000]]

the names like default, direct, sales, support

are dynamic so I can't do jsondata.support

what I tried

ticks = []
for key in jsondata{
    arraynew = [];
    arraynew.push(key)
}

but I don't know how to push the values?

Help please.

5
  • EDIT: arraynew.push(jsondata[key][0][0]) Commented Apr 17, 2014 at 14:34
  • Why put arraynew = []; inside the loop? Commented Apr 17, 2014 at 14:34
  • @LuisMasuelli that push the whole array, i just need the first value Commented Apr 17, 2014 at 14:35
  • @GôTô to take all the dynamic data. Commented Apr 17, 2014 at 14:35
  • @user2208349 Sorry I don't get it. Won't it empty arraynew for each key? Commented Apr 17, 2014 at 14:46

1 Answer 1

4

You just need to access the sub-array.

var ticks = [];
for (var key in jsondata) {
  ticks.push( [ key, jsondata[key][0][0] ] );
}

The expression jsondata[key] gets you the outer array corresponding to each key. Then, jsondata[key][0] gets you the first of the sub-arrays, and adding the final [0] to that gets you the first value in the first sub-array.

Note that you're not guaranteed to get the keys back in any particular order.

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

1 Comment

+1 It works. amazing. thanks. will accept it once the system allows

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.