Javascript使用来自json的值编写循环并将其嵌套数据作为json对象传递给循环

时间:2018-03-10 23:03:10

标签: javascript arrays json

我在 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()来做到这一点,但不确定如何正确使用。

@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"}} }

1 个答案:

答案 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; }