如何从json文件中的两个对象中检索数据?

时间:2016-07-07 07:58:06

标签: angularjs json

如果我有用户记录和订单记录,则保存它们是正确的:

{
    "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"}   
    ]
}

你可以看到我来自SQL世界,所以我保存了这些命令'使用外键的数据,是将这些数据保存为json的正确方法,如果是这样,我怎样才能让所有用户获得订单?

谢谢!

2 个答案:

答案 0 :(得分:0)

将json文件的对象提取为两个变量

var a = value.users;

var b = value.orders;

值只是整个json文件

然后你可以将它们相互匹配,如

一个[0] == .ID湾[0] .ID

答案 1 :(得分:0)

如果您的json对象位于上述结构中,您可以使用此代码过滤订单

In file included from foo.cc:2:0:
foo.h: In constructor ‘Foo::Foo()’:
foo.h:10:13: error: ‘create_a_compile_error’ was not declared in this scope
     Foo() { create_a_compile_error; };
             ^
foo.h: At global scope:
foo.h:7:16: warning: ‘FOO_CONSTANT’ defined but not used [-Wunused-variable]
 const unsigned FOO_CONSTANT = f(4);
                ^

但最好使用sql joint来合并订单并返回像这样的对象

    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
         } 
      }
   }