Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Left join with lowdb

I have two "tables"/arrays, user and order, in my JSON database. It looks like this :

{
  "user": [
    {
      "id": "1",
      "name": "test"
    },
    {
      "id": "2",
      "name": "test"
    },
    {
      "id": "3",
      "name": "test"
    }
  ],
  "order": [
    {
      "user_id": "1",
      "date_order": "2018-01-01",
      "end_order": "2018-01-05"
    },
    {
      "user_id": "2",
      "date_order": "2018-02-01",
      "end_order": "2018-02-05"
    }
  ]
}

I want to retrieve all the users who haven't an order associated to them. So in this case, only the user #3. Is there a specific function to do a left join ? I read the README but I can't figure out how to "join" two "tables". Thanks !

like image 813
HeroJo Avatar asked Oct 15 '22 15:10

HeroJo


1 Answers

You can use filter() on user array and use find() on order array to check if there is any object with user_id equal to id of obj in user array.

const obj = { "user": [ { "id": "1", "name": "test" }, { "id": "2", "name": "test" }, { "id": "3", "name": "test" } ], "order": [ { "user_id": "1", "date_order": "2018-01-01", "end_order": "2018-01-05" }, { "user_id": "2", "date_order": "2018-02-01", "end_order": "2018-02-05" } ] }

const res = obj.user.filter(x => !obj.order.find(a => a.user_id === x.id));
console.log(res);
like image 96
Maheer Ali Avatar answered Nov 02 '22 10:11

Maheer Ali