1

In node js I get flat data from the db. I want to group the data by the main entity.

Example of data that getting from the db (using left join query)

[
{
writer_id:1,
writer_name:'Ben'
book_id:1
book_name:'The special book'
},
{
writer_id:1,
writer_name:'Ben'
book_id:2
book_name:'My second book'
}
]

I need to format the data like this

  [{
    writer_id:1,
    writer_name:'Ben'
    books:
   [{book_id:1
    book_name:'The special book'
    },{book_id:2
    book_name:'My second book'
    }]

    }]

How can I do it using javascript or using knex queries (if it possible)

my code:

return   db.from('arrangement')
            .innerJoin('users as u1', 'arrangement.user_id', 'u1.id')
            .....

            .leftJoin('commercial_papers_status', 'commercial_papers.status_id', 'commercial_papers_status.id')
            .select(['commercial_papers.*', ......)
           .where({
               'commercial_papers.user_id': user.id,
               'commercial_papers.deleted':0
           })

           .then((arrangements) => {


        *************************
TEST FOR GROUPING
************************

            result = arrangements.reduce(function (r, obj) {
                if(obj.id){
                key ='key' + obj.id || '0';
                r[key] = r[key] || [];
                let {id, price, ...rest} = obj;
                //console.log(rest); // { c: 30, d: 40 }
                r[key].push(rest);
                }
                return r;
            }, Object.create(null));




               return result
24sharon
  • 1,859
  • 7
  • 40
  • 65
  • Could you post your code that you've used to do this, so someone can help you. – PrivateOmega May 17 '19 at 11:14
  • you should use lodash or some similar library for that https://stackoverflow.com/questions/40774697/how-to-group-an-array-of-objects-by-key – Mikael Lepistö May 17 '19 at 21:12
  • all the solutions in the url, make the key as an array, this is not what I looking for, I need more than single key. I resolve my issue with coding my exact needs. – 24sharon May 19 '19 at 03:00

0 Answers0