3

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

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

我要创建的地图是:

键(字符串),值(数组)

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

是否有可能做到这一点?:/

提前致谢。

4

3 回答 3

8

演示

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));

输出:

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

于 2013-02-19T17:02:36.667 回答
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"]
// }
于 2013-02-19T17:03:32.577 回答
1

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

于 2013-09-27T04:00:23.083 回答