簡體   English   中英

Javascript使用json的值編寫循環並將其嵌套數據作為json對象傳遞給循環

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM