Avi Hazut Avi Hazut - 4 months ago 13
AngularJS Question

How to retrieve data from two objects in json file?

If I have records for users and also records for orders, it is proper to save them like that:

{
"users": [
{"id": "1", "name": "Allan", "age": "40"},
{"id": "2", "name": "Jack", "age": "50"}
],
"orders": [
{ "id": "1", "item": "item 1", "userId": "1"},
{ "id": "2", "item": "item 3", "userId": "1"},
{ "id": "1", "item": "item 4", "userId": "1"},
{ "id": "1", "item": "item 51", "userId": "1"},
{ "id": "2", "item": "item 4", "userId": "1"}
]
}


as you can see I'm coming from the SQL world so I'm saving the 'orders' data with foreign key, is that the right way to save this data as json and if so how can I get all the users with there orders?

Thanks!

Answer

If your json object is in the above mentioned structure you can use this code to filter the orders

    var oJson = {
   "users": [
         {"id": "1", "name": "Allan", "age": "40"},
         {"id": "2", "name": "Jack", "age": "50"}
   ],
   "orders": [
         { "id": "1", "item": "item 1", "userId": "1"},
         { "id": "2", "item": "item 3", "userId": "1"},
         { "id": "1", "item": "item 4", "userId": "1"},
         { "id": "1", "i`enter code here`tem": "item 51", "userId": "1"},
         { "id": "2", "item": "item 4", "userId": "1"}   
]}
   for(var i=0; i<oJson.users.length;i++){   
      for(var j=0; j<oJson.orders.length;j++){
         if (oJson.users[i].id == oJson.orders[j].userId) {
            console.log( oJson.orders[j].item, oJson.orders[j].userId)
            //your logic here
         } 
      }
   }

But it is better to use sql joints to merge the orders and return the objects like this

 {
"users": [
    {"id": "1", "name": "Allan", "age": "40","orders": [{ "id": "1", "item": "item 1", "userId": "1"},{ "id": "2","item": "item 3", "userId": "1"},{ "id": "1", "item": "item 4", "userId": "1"},{ "id": "1", "item": "item 51", "userId": "1"},{ "id": "2", "item": "item 4", "userId": "1"}   
]},
    {"id": "2", "name": "Jack", "age": "50","orders":[]}
]}