如何转换 JavaScript hashmap?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14963080/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 18:27:49  来源:igfitidea点击:

How to transform JavaScript hashmap?

javascriptjsonmap

提问by msqar

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

我正在尝试<String, Array()>从 json 对象创建地图。想象一下,我得到了这个 json 结构:

[
    {
        "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.

提前致谢。

回答by MrCode

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

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

回答by maerics

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

回答by Binita Bharati

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

Javascript 的 JSON.stringify 将帮助您将任何符合 JSON 的对象模型转换为 JSON 字符串。