How to group and filter fields with JS

Asked

Viewed 133 times

1

I’m trying to get the following result using lodash:

[
 {
   "idpai": 1,
   "pai": "joao",
   "mae": "maria",
   "filhos": [
     {"id": 1, "nome": "joaozinho"},
     {"id": 2, "nome": "pedrinho"}
   ]
 }
]

with the following code:

var lista = [
  {idpai: 1, pai: 'joao', mae: 'maria', idfilho: 1, filho: 'marcos'},
  {idpai: 1, pai: 'joao', mae: 'maria', idfilho: 2, filho: 'joao'},
]

result = _.groupBy(lista, 'idpai')

outworking:

{
   "1": [
      {
         "idpai": 1,
         "pai": "joao",
         "mae": "maria",
         "idfilho": 1,
         "filho": "marcos"
      },
      {
         "idpai": 1,
         "pai": "joao",
         "mae": "maria",
         "idfilho": 2,
         "filho": "joao"
      }
   ]
}

As I am using lodash I am looking for something that can help me, my list comes duplicated like this because it is a relational bank, there is some other way to solve?

2 answers

1


Hello,

Friend I believe that this structure should come from your backend.

I believe that there is nothing more practical than to do with your own hands, I did something, a little gambiarra, but returns its structure:

https://stackblitz.com/edit/js-hmyo8w

0

Amigo uses the alasql link: http://alasql.org/

It will allow you to work as sql in your javascript array.

I hope I helped friend.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.