我如何使用.reduce()按值分組 - 所以如果我有以下內容:
const arr = [
{
id: 1,
value: 'abc',
othervalue: '123'
},
{
id: 2,
value: 'def',
othervalue: '123'
},
{
id: 3,
value: 'def',
othervalue: '123'
},
{
id: 4,
value: 'ghi',
othervalue: '123'
}
]
我要這個 :
{
'abc' : [{id:1, value:'abc', othervalue: '123'}]
'def' : [{id:2, value:'def', othervalue: '123'}, {id:3, value:'def', othervalue:'123'}],
'ghi' : [{id:4, value:'ghi', othervalue: '123'}]
}
我試過了,但沒有用:
arr.reduce( (acc,p) => ({...acc, [p.value]:p }))
uj5u.com熱心網友回復:
你所擁有的很接近,但請確保:
- 拼寫
acc正確 - 保留陣列中的先前值
(acc[p.value]||[]).concat(p) - 提供一個初始值,
{}作為第二個引數
arr.reduce((acc,p) => ({ ...acc, [p.value]: (acc[p.value]||[]).concat(p) }), {})
uj5u.com熱心網友回復:
它不是一個很小的襯里,但它是可讀的
const arr = [{
id: 1,
value: 'abc',
othervalue: '123'
},
{
id: 2,
value: 'def',
othervalue: '123'
},
{
id: 3,
value: 'def',
othervalue: '123'
},
{
id: 4,
value: 'ghi',
othervalue: '123'
}
]
let grouped = arr.reduce((b, a) => {
b[a.value] = b[a.value] || [];
b[a.value].push(a);
return b
}, {})
console.log(grouped)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/421929.html
標籤:
下一篇:如何顯示輸入時選擇的影像?
