0

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.

3
  • added the missing commas if thats what was missing Commented Apr 2, 2020 at 15:15
  • Still invalid syntax. Is comment supposed to be an array? Commented Apr 2, 2020 at 15:17
  • yes, what am i missing. Sorry but yes my goal is an nested array Commented Apr 2, 2020 at 15:17

2 Answers 2

3

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; }

Sign up to request clarification or add additional context in comments.

1 Comment

This solution worked perfectly. Thank you for your help
1

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);

You can do what i've done above or use _.groupBy() from lodash.

1 Comment

Good to know. didnt realize groupBy Lodash function

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.