【发布时间】:2018-03-10 23:03:10
【问题描述】:
我在 myContactsUuids 数组中有一个用户 uuid 列表,使用 forEach() 方法遍历它们并添加使用 new ChatEngine 检索的用户。 myContacts 数组的 User(uuid) 函数。
myContactsUuids = ["john_doe_001", "john_doe_005"];
// set a global array of users
myContacts = {};
myContactsUuids.forEach(function(uuid) {
myContacts[uuid] = new ChatEngine.User(uuid);
});
现在尝试重写它以执行基本相同的操作,但在每个 uuid 下嵌套了额外的数据,并将其作为 JSON 对象传递,用户 uuid 作为字符串在 ChatEngine.User() 函数中。 p>
我现在有这样的用户数据,但可以以任何方式格式化。
myContactsUuids = {"john_doe_001":{"username":"John Doe","avatar_url":"http://someurl"},"john_doe_003":{"username":"Another John Doe","avatar_url":"http://someurl"}};
和 ChatEngine.User(uuid,data) 函数,其中 uuid 是用户 uuid 字符串和数据 json 对象,例如循环中的用户如下所示:
new $scope.ChatEngine.User("john_doe_001", {"username":"John Doe","avatar_url":"http://someurl"});
只是不确定为此编写循环并将所需数据传递给它的最佳方法是什么,然后像简化函数中那样将检索到的用户添加到数组中。也许我可以使用 each() 做到这一点,但不知道如何正确。
@Ele 解决方案有效,只需要结果数组的格式如下:
{ "john_doe_001":{"uuid":"john_doe_001","data":{"username":"John Doe","avatar_url":"http://someurl"}},"john_doe_003":{"uuid":"john_doe_003","data":{"username":"Another John Doe","avatar_url":"http://someurl"}} }
【问题讨论】:
标签: javascript arrays json