2 回答

TA貢獻(xiàn)1810條經(jīng)驗(yàn) 獲得超5個(gè)贊
您的預(yù)期結(jié)果不是有效的。我認(rèn)為comment這里需要一個(gè)對象數(shù)組,例如:
const temp = [{name:"John",review:"Its great",book:"Jungle Book"},{name:"Steve",review:"Learned a lot",book:"Coding Standards"},{name:"Chris",review:"Love it",book:"Coding Standards"},{name:"Jake",review:"Would read again",book:"Jungle Book"}];
const res = Object.values(temp.reduce((ac, { name, review, book }) => {
ac[book] = ac[book] || {book, comment: []}
ac[book].comment.push({name, review})
return ac;
}, {}));
console.log(res);
.as-console-wrapper { max-height: 100% !important; top: 0; }

TA貢獻(xiàn)1785條經(jīng)驗(yàn) 獲得超4個(gè)贊
const arr = [{
name: 'John',
review: 'Its great',
book: 'Jungle Book'
},
{
name: 'Steve',
review: 'Learned a lot',
book: 'Coding Standards'
},
{
name: 'Chris',
review: 'Love it',
book: 'Coding Standards'
},
{
name: 'Jake',
review: 'Would read again',
book: 'Jungle Book'
}];
const result = arr.reduce(function (r, a) {
r[a.book] = r[a.book] || [];
r[a.book].push(a);
return r;
}, Object.create(null));
console.log(result);
你可以做我上面做的或者_.groupBy()
從 lodash 使用。
添加回答
舉報(bào)