Underscore.js分组对象

时间:2017-02-15 16:34:35

标签: json 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 个答案:

答案 0 :(得分: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" } 
]