0

I'm looking to convert key-value JSON code that looks like this :

{
    "AK": "Arkansas",
    "NY": "New York",
    "CA": "California"
}

Into an array, where the key value from the JSON becomes one of the values in the object literals.

0 : {code :"AK", name:"Arkansas"},
1 : {code:"NY", name:"New York"},
2 : {code:"CA", name:"California}

Is there an easy way to do this?

11
  • 1
    for .. in loop is the best way to go for you. Try it. Commented Sep 2, 2014 at 16:15
  • Out of curiosity, why do you want to do this? I ask because there may be a way to achieve your goal another way without having to do this step. Commented Sep 2, 2014 at 16:16
  • 1
    What have you tried so far? What are you having problems with? Do you have problems a) parsing the JSON? b) iterating over the object? c) creating a new array? d) creating a new object? e) adding elements to an array? Commented Sep 2, 2014 at 16:17
  • 2
    @OliverWatkins FYI, there is only one loop required to solve your problem. Commented Sep 2, 2014 at 16:19
  • 1
    @OliverWatkins - this question is not a duplicate, but the accepted answer may be useful in solving your problem: stackoverflow.com/questions/14615669/… Commented Sep 2, 2014 at 16:21

2 Answers 2

2

Use this code:

var obj = {
    "AK": "Arkansas",
    "NY": "New York",
    "CA": "California"
}
var array1 = [];
for (key in obj) {
    array1.push({
        "code": key,
        "name": obj[key]
    });
}
console.log(array1);
Sign up to request clarification or add additional context in comments.

1 Comment

Have you heard something about code formatting and indentation?
1

There are several ways, the most browser compatible is:

var p = [];
//Places would be your initial object
for (x in places) {
     p.push({code: x, name: places[x]})
}

Maybe you should use something like lodash to make things like this easier

1 Comment

Could you please elaborate on how lodash make this easier?

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.