[英]Javascript for each loop only passing 1 value from JSON and not both
[英]Javascript writing loop using value from json and passing it's nested data to loop as json object
我在myContactsUuids数组中有一个用户uuid列表,使用forEach()方法循环通过它们,并将使用新的ChatEngine.User(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()做到这一点,但不确定如何正确。
@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"}} }
您可以将函数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; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.