“JS Group Objects in Array” Código de respuesta

Grupo JavaScript por matriz de objetos de propiedad

function groupArrayOfObjects(list, key) {
  return list.reduce(function(rv, x) {
    (rv[x[key]] = rv[x[key]] || []).push(x);
    return rv;
  }, {});
};

var people = [
    {sex:"Male", name:"Jeff"},
    {sex:"Female", name:"Megan"},
    {sex:"Male", name:"Taylor"},
    {sex:"Female", name:"Madison"}
];
var groupedPeople=groupArrayOfObjects(people,"sex");
console.log(groupedPeople.Male);//will be the Males 
console.log(groupedPeople.Female);//will be the Females
Grepper

Grupo de matriz de JavaScript por

function groupByKey(array, key) {
   return array
     .reduce((hash, obj) => {
       if(obj[key] === undefined) return hash; 
       return Object.assign(hash, { [obj[key]]:( hash[obj[key]] || [] ).concat(obj)})
     }, {})
}


var cars = [{'make':'audi','model':'r8','year':'2012'},{'make':'audi','model':'rs5','year':'2013'},{'make':'ford','model':'mustang','year':'2012'},{'make':'ford','model':'fusion','year':'2015'},{'make':'kia','model':'optima','year':'2012'}];

var result = groupByKey(cars, 'make');

JSON.stringify(result,"","\t");
{
	"audi": [
		{
			"make": "audi",
			"model": "r8",
			"year": "2012"
		},
		{
			"make": "audi",
			"model": "rs5",
			"year": "2013"
		}
	],
	"ford": [
		{
			"make": "ford",
			"model": "mustang",
			"year": "2012"
		},
		{
			"make": "ford",
			"model": "fusion",
			"year": "2015"
		}
	],
	"kia": [
		{
			"make": "kia",
			"model": "optima",
			"year": "2012"
		}
	]
}
Vijaysinh Parmar

JavaScript Group by Key

result = array.reduce((h, obj) => Object.assign(h, { [obj.key]:( h[obj.key] || [] ).concat(obj) }), {})
Successful Snail

JS Group Objects in Array

let group = cars.reduce((r, a) => { console.log("a", a); console.log('r', r); r[a.make] = [...r[a.make] || [], a]; return r;}, {});console.log("group", group);
Bhishma'S

Cómo agrupar una matriz de objetos

const groupBy = (array, key) => {
  // Return the end result
  return array.reduce((result, currentValue) => {
    // If an array already present for key, push it to the array. Else create an array and push the object
    (result[currentValue[key]] = result[currentValue[key]] || []).push(
      currentValue
    );
    // Return the current iteration `result` value, this will be taken as next iteration `result` value and accumulate
    return result;
  }, {}); // empty object is the initial value for result object
};
Better Butterfly

Respuestas similares a “JS Group Objects in Array”

Preguntas similares a “JS Group Objects in Array”

Más respuestas relacionadas con “JS Group Objects in Array” en JavaScript

Explore las respuestas de código populares por idioma

Explorar otros lenguajes de código