Syl*_*lar 0 javascript underscore.js
我似乎无法正确地表达这一点,因为我需要按date和分组foo:
// 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
Run Code Online (Sandbox Code Playgroud)
我在这里变得有点复杂,所以我使用下划线来减轻复杂性。这可能吗?
然后我会做一些类似的事情,我可以使用_.pluck:
Object.keys(grouped).map( dateKey => Object.keys(grouped[dateKey]).map(fooKey => console.log( grouped[dateKey][fookey][0] )) )
Run Code Online (Sandbox Code Playgroud)
这在最高级别上看起来确实是错误的。
预期结果类似于:
DATE // key
|
|___ FOO // key
|
|__ array foo objects
Run Code Online (Sandbox Code Playgroud)
list.reduce((acc, item) => {
const key1 = item.date
const group1 = acc[key1] || {}
const key2 = item.foo
const group2 = group1[key2] || []
return {
...acc,
[key1]: {
...group1,
[key2]: group2.concat(item)
}
}
}, {})
Run Code Online (Sandbox Code Playgroud)
let grouped = {}
list.forEach((item) => {
// Create an empty object if this key has not already been set:
grouped[item.date] = grouped[item.date] || {}
// Create an empty list if this key has not already been set:
grouped[item.date][item.foo] = grouped[item.date][item.foo] || []
// Push the item to our group:
grouped[item.date][item.foo].push(item)
})
Run Code Online (Sandbox Code Playgroud)
在 python 中,这将是:
from collections import defaultdict
_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 = defaultdict(lambda: defaultdict(list))
for item in _list:
grouped[item['date']][item['foo']].append(item)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1248 次 |
| 最近记录: |