How to convert JavaScript hashmap?

I am trying to create a map <String, Array()>

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 will be:

key (string), value (array)

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

      

Can I do this?: /

Thanks in advance.

+3


source to share


3 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:

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

+8


source


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

      



+3


source


Javascript JSON.stringify helps you convert any JSON compatible object model to JSON string.

+1


source







All Articles