1

I have a JSON Object that looks like this that I created with a java hashmap.

{"1":895,"2":827,"3":1429,"4":14,"5":1,"6":2,"10":2}

My question can go either way is there any way to either convert this JSON object to an associative js array such as

{ 
  d:[
    { 
    'Month' : 1,
    'Count' : 895
    }
    { 
    'Month' : 2,
    'Count' : 827
    }
    { 
    'Month' : 3,
    'Count' : 1429
    }
    { 
    'Month' : 4,
    'Count' : 14
    }
    { 
    'Month' : 5,
    'Count' : 1
    }
    { 
    'Month' : 6,
    'Count' : 2
    }
    { 
    'Month' : 10,
    'Count' : 2
    }
  ]
}

or otherwise convert it into a java script 2d array such as

newArray = [[1, 895][2,827][3,1429][4,14][5,1][6,2][10,2]];

I have researched and researched and I keep running across a lot of great things but none particularly for this instance. Any help would be great!

2 Answers 2

1

Something like this would work:

 newArray = [];
 for(key in myArray)
    newArray.push({"Month": key, "Count": myArray[key]});
Sign up to request clarification or add additional context in comments.

2 Comments

I honestly wish I could accept both answers because they were both spot on, yours is short and to the point. However I did accept the other answer simply because of the links to the information and it was the first one I came across and tried, great answer though and keep up the great work. I really appreciate your help.
Not a problem! The other answer is more informative and definitely deserves recognition! Plus, I reaaally ought to have declared newArray and key with var to avoid scope issues.
0

For example you can do it like this:

var obj = {"1":895,"2":827,"3":1429,"4":14,"5":1,"6":2,"10":2}

var result = {d: Object.keys(obj).map(function(key) {
    return {Month: Number(key), Count: obj[key]}
})};

alert(JSON.stringify(result, null, '    '));

Or you can use more traditional way of looping with for in loop:

var obj = {"1":895,"2":827,"3":1429,"4":14,"5":1,"6":2,"10":2}
var result = {d: []};

for (var key in obj) {
    result.d.push({Month: Number(key), Count: obj[key]});
}

alert(JSON.stringify(result, null, '    '));

More about methods:

Comments

Your Answer

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