3

i'm trying to create a <String, Array()> map from a json object. Imagine i got this json structure:

[
    {
        "userId": "123123",
        "password": "fafafa",
        "age": "21"
    },
    {
        "userId": "321321",
        "password": "nana123",
        "age": "34"
    }
]

The map i want to create would be:

key (string), value (array)

{
    "userId": [
        "123123",
        "321321"
    ],
    "password": [
        "fafafa",
        "nana123"
    ],
    "age": [
        "21",
        "34"
    ]
}

Is it possible to do this? :/

Thanks in advance.

7
  • There is no such thing as a "json object" and I don't see what can be the object you display. Is that a string you receive ? Commented Feb 19, 2013 at 16:58
  • Best to explain what you want to do with that map, because it may be that you can just use the object. Commented Feb 19, 2013 at 16:58
  • 2
    Your "JSON structure" is not JSON at all... Commented Feb 19, 2013 at 16:59
  • I don't get the point of popnoodles' edit... Commented Feb 19, 2013 at 17:00
  • @dystroy OP had used characters that were not being displayed because they had not indented the code. Did you not compare the two versions before commenting? Commented Feb 19, 2013 at 17:01

3 Answers 3

8

Demo

var json = '[{"userId" : "123123", "password": "fafafa", "age": "21"}, {"userId" : "321321", "password" : "nana123", "age" : "34"}]';

var list = JSON.parse(json);
var output = {};

for(var i=0; i<list.length; i++)
{
    for(var key in list[i])
    {
        if(list[i].hasOwnProperty(key))
        {
            if(typeof output[key] == 'undefined')
            {
                output[key] = [];
            }
            output[key].push(list[i][key]);
        }
    }
}

document.write(JSON.stringify(output));

Outputs:

{"userId":["123123","321321"],"password":["fafafa","nana123"],"age":["21","34"]}

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

2 Comments

you are a genius! that's what i needed. Thanks! The thing is, how do i create the map dinamically to String, Array() if i don't know all the keys names?
@user59574 I've edited it to work without having to define the keys.
3
function mergeAttributes(arr) {
  return arr.reduce(function(memo, obj) { // For each object in the input array.
    Object.keys(obj).forEach(function(key) { // For each key in the object.
      if (!(key in memo)) { memo[key] = []; } // Create an array the first time.
      memo[key].push(obj[key]); // Add this property to the reduced object.
    });
    return memo;
  }, {});
}

var json = '[{"userId" : "123123", "password": "fafafa", "age": "21"}, {"userId" : "321321", "password" : "nana123", "age" : "34"}]';

mergeAttributes(JSON.parse(json));
// {
//   "userId": ["123123", "321321"],
//   "password": ["fafafa", "nana123"],
//   "age": ["21", "34"]
// }

5 Comments

@user59574: see the following ECMAScript 5th Edition functions - Array.reduce, Object.keys, and Array.forEach.
Nice example usage of ECMAScript 5 but beware this won't work on anything older than Internet Explorer 9.
@MrCode: yes, quite true. IE<9 does not support these standard JavaScript functions that were added in a specification that was published in late 2009.
@maerics which is a shame because there are some nice modern features in that spec.
@maerics hey, now is showing "arr.reduce is not a function" what's happening? (Firefox and Chrome ) :(
1

Javascript's JSON.stringify will help you to convert any JSON compliant object model into a JSON string.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.