0

I have a JSON object in JQuery that looks like:

["state":"06","population":9},{"state":"32","population":13},{"state":"01","population":4},

I want to end up with a JSON object like:

{"06":9,"32":13,"01":4}

How would I do this in JQuery?

Thanks!

1
  • Iterate over the array and copy the values into a new object? Don't really see the problem.. of course you have to first parse the JSON to a JavaScript array. Have a look at the MDN JavaScript Guide to learn the basics about how to work with arrays and objects: developer.mozilla.org/en/JavaScript/Guide Commented Apr 15, 2012 at 2:33

1 Answer 1

1

you would want to use the .each method. If my_array holds the original array you describe, this ought to do it:

var result = {};
$.each(my_array, function(index, val) {
  result[val.state] = val.population;
});
Sign up to request clarification or add additional context in comments.

3 Comments

(result ends up with the output you describe)
Instead of having the arguments index, val, you can omit those and use result[this.state] = this.population. I'm not really sure which is better per se but I just figured I'd post this for completeness.
It's a good point. I'm in the habit of using the short syntax only when iterating over a jQuery collection and following forEach style (albeit in reverse—never got that!) for other types.

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.