Javascript使用json中的值编写循环并传递它';将嵌套数据作为json对象循环
我在myContactsUuids数组中有一个用户uuid列表,使用forEach()方法循环这些uuid,并将通过new ChatEngine.user(uuid)函数检索到的用户添加到myContacts数组中Javascript使用json中的值编写循环并传递它';将嵌套数据作为json对象循环,javascript,arrays,json,Javascript,Arrays,Json,我在myContactsUuids数组中有一个用户uuid列表,使用forEach()方法循环这些uuid,并将通过new ChatEngine.user(uuid)函数检索到的用户添加到myContacts数组中 myContactsUuids = ["john_doe_001", "john_doe_005"]; // set a global array of users myContacts = {}; myContactsUuids.forEach(function(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下嵌套额外的数据,并在ChatEngine.user()函数中将其作为JSON对象和用户uuid作为字符串传递
我现在有这样的用户数据,尽管可以以任何方式格式化
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,数据)函数,其中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"}} }
您可以使用函数
对象。条目
和函数映射
var result = Object.entries(myContactsUuids)
.map(([uuid, data]) => ({ [uuid]: new $scope.ChatEngine.User(uuid, data) }));
示例代码片段:
var-ChatEngine={
用户:函数(uuid、数据){
this.uuid=uuid;
这个数据=数据;
}
}
var myContactsUuids={“john_doe_001”:{“username”:“john doe”,“avatar_url”:”http://someurl},“john_doe_003”:{“用户名”:“另一个john doe”,“化身url”:http://someurl"}};
var result=Object.entries(myContactsUuids)
.map(([uuid,data])=>({[uuid]:新的ChatEngine.User(uuid,data)});
控制台日志(结果)代码>
。作为控制台包装{max height:100%!important;top:0;}
这很好,但如何使结果数组的格式与第一个示例中的myContacts相同,现在得到的是编号/索引数组。也许可以用不同的方式编写map(),而不需要对其进行转换?@Aivaras你的意思是,使用函数forEach
?不,刚才的结果数组是这样的[{“john_doe_1”:{“data”:{“}},{“john_doe_2”:{“data”:{“}}]所以每个用户都被索引了,需要它是这样的[{“john u doe__1”:{“data”:}},{“john u doe 2”:{“数据:{”“}}}],不知道如何使用。@Aivaras,但这是一个只有一个对象的数组。你想要那个输出吗?还是想要这个:{“john_doe_1”:{“data”:{“2”:1},“john_doe_2”:{“data”:{“a”:1}}
?是的,像这样,抱歉缩短了注释:)所有相同的数据使用(用户名,头像url)只需要像这样的格式数组。