Zeus :
how can I convert this array to a new nested array based on a value within the array
CURRENT ARRAY
[{
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'
}]
LOOKING TO MAKE THIS NESTED ARRAY
[{
book: 'Jungle Book',
comment: [{
name: 'Jake',
review: 'Would read again'
},
{
name: 'John',
review: 'Its great'
}]
},
{
book: 'Coding Standards',
comment: [{
name: 'Chris',
review: 'Love it'
},
{
name: 'Steve',
review: 'Learned a lot'
}]
}]
Any help or tips would be greatly appreciated.
palaѕн :
Your expected result is not a valid one. I think comment
here needs to be an array of object like:
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; }
Guess you like
Origin http://10.200.1.11:23101/article/api/json?id=390908&siteId=1