我在 myContactsUuids 数组中有一个用户uuid列表,使用 forEach()方法循环遍历它们并添加用新ChatEngine检索的用户。用户(uuid)功能为 myContacts 数组。
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()函数中的字符串。
我现在有这样的用户数据,但可以以任何方式格式化。
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()来做到这一点,但不确定如何正确使用。
{ "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"}} }
答案 0 :(得分:1)
您可以将函数Object.entries
与函数map
var result = Object.entries(myContactsUuids)
.map(([uuid, data]) => ({ [uuid]: new $scope.ChatEngine.User(uuid, data) }));
示例摘录
var ChatEngine = {
User: function(uuid, data) {
this.uuid = uuid;
this.data = data;
}
}
var myContactsUuids = {"john_doe_001":{"username":"John Doe","avatar_url":"http://someurl"},"john_doe_003":{"username":"Another John Doe","avatar_url":"http://someurl"}};
var result = Object.entries(myContactsUuids)
.map(([uuid, data]) => ({ [uuid]: new ChatEngine.User(uuid, data) }));
console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }

使用函数reduce
构建所需的输出:
{
"john_doe_1": {
"data": {"2": 1}
},
"john_doe_2": {
"data": {"a": 1}
}
}
var ChatEngine = {
User: function(uuid, data) {
this.uuid = uuid;
this.data = data;
}
}
var myContactsUuids = {"john_doe_001":{"username":"John Doe","avatar_url":"http://someurl"},"john_doe_003":{"username":"Another John Doe","avatar_url":"http://someurl"}},
result = Object.entries(myContactsUuids)
.reduce((a, [uuid, data]) => {
a[uuid] = new ChatEngine.User(uuid, data);
return a;
}, {});
console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }