1

I get a JSON data with this format:

{
 key1: val1,
 key2: val2,
 key3: val3,
 key4: val4,
 ..
}

Now I want to change it to another format in Javascript:

[
    {key: "key1", value: value1},
    {key: "key2", value: value2},
    {key: "key3", value: value3},
    {key: "key4", value: value4},   
    ...     
]

Is there some libraries that can do this? Or I have to write a function?

Please give me some tips! Thanx!

3
  • 1
    That’s a function that is written within a minute … Commented Nov 11, 2013 at 14:42
  • really? Today is the first day I use javascript. I am not quite familiar with it. I think I should get each item in the raw data, get key and value, then put them togerther Commented Nov 11, 2013 at 14:44
  • @CBroe But I don't know how to do the string operation. Commented Nov 11, 2013 at 14:45

1 Answer 1

7
var newObject = Object.keys(originalObject).map(function(k) { 
  return { key: k, value: originalObject[k] };
});
Sign up to request clarification or add additional context in comments.

2 Comments

Where can i study more about this..? Can you provide a useful link? (I meant the map and key functions which i never knew existed)
@NevinMadhukarK: I don't have a useful link that happens to cover both those two functions, other than pointing to the JavaScript references. MDN is a good resource in general. You can find all the functions available on Object here. You should also check out the reference for Array.prototype, it has a lot of good stuff. Besides map, read up on reduce, filter, some, every.

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.