给定一个对象数组,如何根据深度为n的属性对对象排序

Given an array of objects how do I sort the objects by a property in depth n

本文关键字:属性 排序 对象 深度 一个对象 数组 何根      更新时间:2023-09-26

我有一个对象数组,我希望通过一些分组属性数据和一个字符串告诉我哪个属性分组(例如:'Organization'或'Organization. name ')

我需要写一个函数,它接收看起来像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'}]},]
    }
]

我该怎么做呢?我目前的尝试非常臃肿,而且考虑到大量的数据集,需要花费很长时间。

特别爱发牢骚的人!:解决这个问题的函数需要能够在不知道"group by property"是否在深度1或2(例如:'Organization'或'Organization. longname ')的情况下解决它。

my Something:

// 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:主实现显然不能处理所有可能的错误。根据实际需求,改进它并不难。