在C#中创建嵌套对象,如C#中的groupby

时间:2009-06-26 15:32:31

标签: c# javascript object group-by

IList<Customer> Customers =
            flat.GroupBy(cust => new { cust.ReferenceNumber, cust.Name, cust.Address })
                .Select(c => new Customer()
                {
                    ReferenceNumber = c.Key.ReferenceNumber,
                    Name = c.Key.Name,
                    Address = c.Key.Address,
                    Orders = c.Select(o => new Order()
                    {
                        OrderId = o.OrderId,
                        ProductName = o.ProductName,
                        Description = o.Description,
                        Amount = o.Amount
                    }).ToList()
                }).ToList()

是否可以在Javascript中使用平面列表并将其转换为嵌套对象? 一个通用的解决方案是??

2 个答案:

答案 0 :(得分:16)

虽然这是一个老问题,但我认为我会提供更优雅的解决方案:

/**
 * Groups an array of objects by one or more keys
 * 
 * @param array arr       The array of objects to group
 * 
 * @param string|function A string representing the child property to group by
 *                        or a function that returns an array of one or more properties.
 * 
 * @returns               An object with keys representing the grouping properties, 
 *                        finally holding an array of records that fell into 
 *                        those groups.
 */
var group = function( items, by ) {
    var groups = {},
        group,
        values,
        i = items.length,
        j,
        key,
        group_keys;

    // make sure we specified how we want it grouped
    if( !by ) { return items; }
    while( i-- ) { 

        // find out group values for this item
        values = ( typeof(by) === "function" && by( items[i] ) || 
                   typeof items[i] === "object" && items[i][by] || 
                   items[i] );

        // make sure our group values are an array
        values = values instanceof Array && values || [ values ];

        // recursively group
        group = groups;
        for( j = 0; j < values.length; j++ ) {
            key = values[j];
            group = ( group [key] || ( group [key] = j === values.length - 1 && [] || {} ) );
        }

        // for the last group, push the actual item onto the array
        group = ( group instanceof Array && group || [] ).push( items[i] );
    }

    return groups;
};

用这个来打电话:

var items = [
    { "id" : 1, "name" : "foo",  "category" : "a" },
    { "id" : 2, "name" : "foo",  "category" : "a" },
    { "id" : 3, "name" : "bar",  "category" : "b" },
    { "id" : 4, "name" : "free", "category" : "a" },
    { "id" : 5, "name" : "beer", "category" : "b" },
    { "id" : 6, "name" : "foo",  "category" : "b" }
];

var groups = group( items, function( item ) { return [ item.category, item.name ]; } );

产生这个:

{
    b: {
        foo: [
            {
                id: 6
                name: foo
                category: b
            }
        ]
        beer: [
            {
                id: 5
                name: beer
                category: b
            }
        ]
        bar: [
            {
                id: 3
                name: bar
                category: b
            }
        ]
    }
    a: {
        free: [
            {
                id: 4
                name: free
                category: a
            }
        ]
        foo: [
            {
                id: 2
                name: foo
                category: a
            }
            {
                id: 1
                name: foo
                category: a
            }
        ]
    }
}

无论如何,希望这有助于某人。

答案 1 :(得分:2)

是。

您可以在JavaScript中传递函数,这与C#代码中的lambda表达式的作用相同。以JQuery的“each”为例:

$('div.several').each(function() { 
  // Do something with the current div.
});

您还可以非常轻松地创建嵌套对象:

var outer = {
    inner1: {
        val1: 'a',
        val2: 'b'
    },
    inner2: {
        val1: 'c',
        val2: 'd'
    }
};

当然,你可以动态地做到这一点,而不是一次性完成:

var outer = {};
outer.inner1 = {};
outer.inner1.val1 = 'a';
...

然后,为了做你想要的,你需要使用数组:

var result = [];
for (var i=0; i<x; ++i) {
  result[result.length] = GetIndividualResult(i);
}