2017-02-15 98 views
0

是更多鈔票,以組對象,並結合Underscore.js所有屬性是這樣的:Underscore.js分組對象

[ 
    { menu: "Setting", role: "admin" }, 
    { menu: "Setting", role: "user" }, 
    { menu: "Setting", role: "developer" }, 
    { menu: "Application", role: "admin" }, 
    { menu: "Application", role: "user" }, 
] 

弄成這個樣子:

[ 
    { menu: "Setting", admin: "OK", user: "OK", developer: "OK"}, 
    { menu: "Application", admin: "OK", user: "OK"}, 
] 
+1

是的,也有可能與常規的老JS一樣。 – Adam

+0

是的,我一直在嘗試與常規的JS,但我最終與循環,需要時間和內存,所以我想尋找替代品,如underscore.js :) – stkertix

回答

0
_.map(_.groupBy(arr, 'menu'), function(roles, menu) { 
    var entry = {menu: menu}; 
    _.each(roles, function(role) { entry[role.role] = "OK"; }); 
    return entry; 
}) 

我假設你後面的輸出是:

[ 
    { "menu": "Setting", "admin": "OK", "user": "OK", "developer": "OK" }, 
    { "menu": "Application", "admin": "OK", "user": "OK" } 
] 
+0

woaah,它適用於這樣一個簡單的腳本。感謝您的回答。 :d – stkertix