给定一个对象数组,如何通过深度为n的属性对对象进行排序

时间:2014-06-27 06:28:23

标签: javascript sorting

我有一个对象数组,我希望通过一些分组属性数据和一个字符串来排序,告诉我要分组的属性(例如:' Organization'或' Organization.Name&#39 ;)

我需要编写一个函数,该函数接收看起来像beforeData的数据并返回afterData

输入:

beforeData = [
{'name':'John Doe', 'Id':1, 'Organizations':[{'Id':12, 'LongName': 'Group A'},{'Id':13, 'LongName': 'Group B'}]},
{'name':'FooBar', 'Id':2, 'Organizations':[{'Id':13, 'LongName': 'Group B'},{'Id':14, 'LongName': 'Group C'}]},
{'name':'Kristine Bell', 'Id':3, 'Organizations':[{'Id':12, 'LongName': 'Group A'}]},
{'name':'Adrian P', 'Id':4, 'Organizations':[{'Id':12, 'LongName': 'Group A'}]}
]

输出:

    afterData = [
    {   
        'Group': 'Group A', 
        'entities':[
            {'name':'Adrian P', 'Id':4, 'Organizations':[{'Id':12, 'LongName': 'Group A'}]},
            {'name':'Kristine Bell', 'Id':3, 'Organizations':[{'Id':12, 'LongName': 'Group A'}]},
            {'name':'John Doe', 'Id':1, 'Organizations':[{'Id':12, 'LongName': 'Group A'},{'Id':13, 'LongName': 'Group B'}]}]
    },
    {   
        'Group': 'Group B', 
        'entities':[
            {'name':'John Doe', 'Id':1, 'Organizations':[{'Id':12, 'LongName': 'Group A'},{'Id':13, 'LongName': 'Group B'}]},
            {'name':'FooBar', 'Id':2, 'Organizations':[{'Id':13, 'LongName': 'Group B'},{'Id':13, 'LongName': 'Group C'}]},]
    },
    {   
        'Group': 'Group C', 
        'entities':[
            {'name':'FooBar', 'Id':2, 'Organizations':[{'Id':13, 'LongName': 'Group B'},{'Id':13, 'LongName': 'Group C'}]},]
    }
]

我将如何完成此任务?我目前的尝试非常臃肿,并且在给定大量数据的情况下永远都是如此。

特别踢球者!:解决此问题的功能需要能够在不事先知道" 属性"之前解决它的问题。深度为1或2(例如:'组织'或' Organization.LongName')。

1 个答案:

答案 0 :(得分:4)

来自我的东西:

// this function performs data extraction from an object
// the first argument is a name of the property to be extracted
// it might be just a 1st level deep value like `name`
// or nested like `foo.bar.baz`
// in case if one of intermediate items is an array - an array of
// results is returned
function dot(name, obj) {
    if (!name) {
        return obj;
    }

    var match = name.match(/^([^.]+)(?:\.(.*))?$/),
        head = match[1],
        tail = match[2];

    if (Array.isArray(obj)) {
        return obj.map(function(item) {
            return dot(name, item);
        });
    }

    if (obj === null || typeof obj != 'object') {
        return null;
    }

    return dot(tail, obj[head]);
}

// this function accepts an array of data and a key to group by
// as a result it returns an object with keys equal to a group by key
// and values that hold that key
function groupBy(data, key) {
    return data.reduce(function(result, item) {
        var keys = dot(key, item);
        if (!Array.isArray(keys)) {
            keys = [keys];
        }

        keys.forEach(function(key) {
            if (!(key in result)) {
                result[key] = [];
            }

            result[key].push(item);
        });

        return result;
    }, {});
}

console.log(groupBy(beforeData, 'Organizations.LongName'));

JSFiddle:http://jsfiddle.net/w8N4j/

现在可以轻松地将其重新格式化为您想要的任何其他格式。

例如,从这里得到问题的确切格式是一个微小的变换器:

function transformerExample(hash) {
    var result = [];
    for (var key in hash) if (hash.hasOwnProperty(key)) {
        result.push({
            Group: key,
            entities: hash[key]
        });
    }

    return result;
}

PS:主要实现显然可能无法处理所有可能的错误。根据实际要求,不难改进它。