crear objetos anidados en JavaScript como GroupBy en C #
-
20-08-2019 - |
Pregunta
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()
Está tomando una lista plana y convertirla en un objeto anidado posible en Javascript? Una solución genérica que es ??
Solución
Sí.
Puede pasar alrededor funciones en JavaScript, que serviría al mismo propósito que las expresiones lambda en el código C #. Tomar el uso de jQuery de "cada uno" como un ejemplo:
$('div.several').each(function() {
// Do something with the current div.
});
También puede crear objetos anidados con bastante facilidad:
var outer = {
inner1: {
val1: 'a',
val2: 'b'
},
inner2: {
val1: 'c',
val2: 'd'
}
};
Por supuesto, usted puede hacer eso de forma dinámica, en lugar de todos a la vez:
var outer = {};
outer.inner1 = {};
outer.inner1.val1 = 'a';
...
A continuación, para hacer lo que está buscando, tendrá que utilizar matrices:
var result = [];
for (var i=0; i<x; ++i) {
result[result.length] = GetIndividualResult(i);
}
Otros consejos
A pesar de que esta es una vieja pregunta, pensé que ofrecería una solución más elegante:
/**
* 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;
};
Llamada con esto:
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 ]; } );
Rendimientos esto:
{
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
}
]
}
}
De todos modos, espero que esto ayude a alguien.