我似乎无法正确地说出这句话,因为我需要按datefoo进行分组:

// Using date as numbers for clear example
// date key should be grouped into a key
// Under that key (date), I should see another key of "foo"

let list = [
  { date: "1", foo: "me", result: "meFoo"},
  { date: "1", foo: "me2", result: "meYou"},
  { date: "1", foo: "me3", result: "meHe"},
  { date: "2", foo: "me", result: "meHim"},
  { date: "2", foo: "me2", result: "meHim"}
]

let grouped = _.groupBy(list, "date") // keys ie 1, 2

// I need another key under the date key, possible?
let grouped = _.groupBy(list, "date", (val) => _.groupBy(val), "foo") // result not expected


我在这里有点复杂,所以我使用下划线来减轻复杂性。这可能吗?

然后,我将执行类似的操作,可以使用_.pluck

Object.keys(grouped).map( dateKey => Object.keys(grouped[dateKey]).map(fooKey => console.log( grouped[dateKey][fookey][0] )) )


从最高层次看,这确实是错误的。

预期结果如下所示:

DATE // key
 |
 |___ FOO // key
       |
       |__ array foo objects

最佳答案

这将为您提供所需的阵列。

_.map(_.groupBy(list, 'date'), (value, key) => ({[key]: _.groupBy(value, 'foo')}))


我希望你想要这样的结果:



var list = [{ date: "1", foo: "me", result: "meFoo" }, { date: "1", foo: "me2", result: "meYou" }, { date: "1", foo: "me3", result: "meHe" }, { date: "2", foo: "me", result: "meHim" }, { date: "2", foo: "me2", result: "meHim" }],
    grouped = _.map(_.groupBy(list, 'date'), (value, key) => ({[key]: _.groupBy(value, 'foo')}));

console.log(grouped);

.as-console-wrapper { max-height: 100% !important; top: 0; }

<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

07-24 17:56
查看更多