如何通过“外键”组合json对象关系 [英] How to combine json object by "foreign key" relationship

查看:100
本文介绍了如何通过“外键”组合json对象关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个不同的休息资源返回两个对象。

I have two objects returned from two different rest resources.

{
"id": 1,
"username": "jdoe"
}

{
"role_id": 1,
"role": "developer",
"members": [
    1,
    3,
    5
]
}

我想使用普通的ole javascript将这两个对象组合成一个id在member数组中的对象,这样我就可以获得一个像角色一样的对象作为顶级节点,然后在下面列出该角色的用户。

I'd like to use plain ole javascript to combine these two objects based into one where id is in the members array, so that i get back an object like has roles as the top node, then lists users of that role underneath.

轻松完成?

推荐答案

<几周前,我遇到了一个类似的问题,一组10个AJAX调用,我想将它们组合在一起。一种简单的方法是从 id 值创建一个查找表,然后使用查找表来组合结果。以下是使用多个用户和多个角色的示例:

I had a similar problem a couple weeks ago with a set of 10 AJAX calls that I wanted to mesh together. A simple method is to create a lookup table from the id values, then use the lookup table to combine the results. Here's an example using multiple users and multiple roles:

var users = [
    { "id": 1, "username": "jdoe" },
    { "id": 3, "username": "dbob" },
    { "id": 5, "username": "jske" }
];
var roles = [
    { "role_id": 1, "role": "developer", "members": [1,3,5] },
    { "role_id": 2, "role": "admin", "members": [5] }
];

// create lookup table
for (var i = 0; i < users.length; i++)
    users.lookup[users[i].id] = users[i];

// populate members from users with lookup table
for (var i = 0; i < roles.length; i++)
    for (var j = 0; j < roles[i].members.length; j++)
        roles[i].members[j] = users.lookup[roles[i].members[j]];

现在角色中的成员是对用户的引用,而不仅仅是id的引用:

Now the members in roles are references to the users rather than just the id's:

[
  { "role_id": 1, "role": "developer", "members":
    [{ "id": 1, "username": "jdoe" },
     { "id": 3, "username": "dbob" },
     { "id": 5, "username": "jske" }] },
  { "role_id": 2, "role": "admin", "members": 
    [{ "id": 5, "username": "jske" }] }
]

您可以在以下角色中引用用户名:

And you can reference the usernames in a role like this:

for (var i = 0; i < roles[0].members.length; i++)
    alert(roles[0].members[i].username);

演示: http://jsfiddle.net/2aqR5/1/

这篇关于如何通过“外键”组合json对象关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆