我的目标是从JSON对象开始。这不是我将要使用的对象,但是它将用于示例。

 var json = [
    {"id":"1","age":"20", "region":"Y"},
    {"id":"2", "age":"20", "region":"X"},
    {"id":"3", "age":"31", "region":"Z"},
    {"id":"4", "age":"35", "region":"Q"}
];


可以说,我的目标是根据年龄对区域进行分类。我希望创建一个将json拆分为以下内容的函数:

var newObj = [
              [
                {"id":"1","age":"20", "region":"Y"},
                {"id":"2", "age":"20", "region":"X"}
              ],
              [
                {"id":"3", "age":"31", "region":"Z"}
              ],
              [
               {"id":"4", "age":"35", "region":"Q"}
              ]
            ];


然后,我可以对新数组进行排序。我永远不会知道年龄是多少,或者我将需要创建多少个数组。谢谢您的帮助。

最佳答案

我想你想要这个:

function groupByProperty(list, prop) {
    var hash = {};
    list.forEach(function(obj) {
        var value = obj[prop];

        if (!(value in hash)) {
            hash[value] = [];
        }

        hash[value].push(object);
    });

    return Object.keys(hash).map(function(key) {
        return hash[key];
    });
}

var newObj = groupByProperty(json, 'age');

09-16 17:49