Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to transform JavaScript hashmap?

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.

like image 620
msqar Avatar asked Feb 26 '26 21:02

msqar


1 Answers

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"]}

like image 54
MrCode Avatar answered Mar 01 '26 11:03

MrCode



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!