Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 group array objects by field type

Is there a terse es6 functional way to group items by type in that it's immutable?

accounts.json

   [
         {"account": {"name": "Bob's credit", "type": "credit", "id": "1"}},
         {"account": {"name": "savings", "type": "savings", "id": "2"}},
         {"account": {"name": "vacation savings", "type": "savings", "id": "3"}},
         {"account": {"name": "son's savings", "type": "savings", "id": "4"},
         {"account": {"name": "wife's credit card", "type": "savings", "id": "5"}
   ]

Expected

[
{"savings": [
    {"account": {"name": "savings", "type": "savings", "id": "2"}},
    {"account": {"name": "vacation savings", "type": "savings", "id": "3"}},
    {"account": {"name": "son's savings", "type": "savings", "id": "4"}
]},

{"checking": [
   {"account": {"name": "wife's credit card", "type": "savings", "id": "5"}
]
like image 776
chrisjlee Avatar asked Mar 30 '18 13:03

chrisjlee


People also ask

How do you group objects in an array?

The most efficient method to group by a key on an array of objects in js is to use the reduce function. The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in a single output value.

How do I use groupBy in JavaScript?

groupBy(dog => { return dog. breed; }); We can use the new groupBy function by calling it on the array instance, just like using a map , filter , or reduce function. groupBy takes a callback function which is called for each element in the array in ascending order.

What are array methods in es6?

An array is a homogeneous collection of values. It is a single variable that is used to store different elements. It is often used when we want to store a list of elements and access them by a single variable.

Can we have array of objects in JavaScript?

Array Elements Can Be Objects JavaScript variables can be objects. Arrays are special kinds of objects. Because of this, you can have variables of different types in the same Array.


1 Answers

You can use Array#reduce to group your list by its elements inner type property :

const data = [
     {"account": {"name": "Bob's credit", "type": "credit", "id": "1"}},
     {"account": {"name": "savings", "type": "savings", "id": "2"}},
     {"account": {"name": "vacation savings", "type": "savings", "id": "3"}},
     {"account": {"name": "son's savings", "type": "savings", "id": "4"}},
     {"account": {"name": "wife's credit card", "type": "savings", "id": "5"}}
];

const res = data.reduce((acc, curr) => {
  if(!acc[curr.account.type]) acc[curr.account.type] = []; //If this type wasn't previously stored
  acc[curr.account.type].push(curr);
  return acc;
},{});

console.log(res);
like image 195
Zenoo Avatar answered Oct 14 '22 19:10

Zenoo