0

I have an object looking like this

const item = {
  id: 123,
  type: 'book',
  sections: [{
    type: 'section',
    id: '456',
    index: 1,
    lessons: [{
      type: 'lesson',
      id: 789,
      index: 1
    },
    {
      type: 'lesson',
      id: 999,
      index: 2
    }
    ]
  }, {
    type: 'section',
    index: 2,
    id: 321,
    lessons: [{
      type: 'lesson',
      id: 444,
      index: 1
    },
    {
      type: 'lesson',
      id: 555,
      index: 2
    }
    ]
  }]
}

It should be assumed that there are more objects in sections and lessons array. I want to create a new object like this

result = [{
  section: 456,
  lessons: [789, 999]
}, {
  section: 321,
  lessons: [444, 555]
}]

I tried this loop but this just pushes indexes and not lesson's ids


let obj = {};
let sectionWithLessons = [];
let lessons = []

for (const i in item.sections) {
  obj = {
    sectionId: item.sections[i].id,
    lessonIds: item.sections[i].lessons.map((lesson) => {
      return lessons.push(lesson.id)
    }),
  };
  sectionWithLessons.push(obj);
}

console.log(sectionWithLessons);

How can i do this correctly and preferably with good performance in consideration?

0

2 Answers 2

1

I believe the best/shortest thing is to use the map function, like:

const result2 = item.sections.map(({id, lessons}) => ({
  id, 
  lessons: lessons.map(({id: lessionId}) => lessionId)
}))
Sign up to request clarification or add additional context in comments.

Comments

1

I would suggest using Array.map() to convert the item sections to the desired result.

We'd convert each section into an object with a section value and lessons array.

To create the lessons array, we again use Array.map() to map each lesson to a lesson id.

const item = { id: 123, type: 'book', sections: [{ type: 'section', id: '456', index: 1, lessons: [{ type: 'lesson', id: 789, index: 1 }, { type: 'lesson', id: 999, index: 2 } ] }, { type: 'section', index: 2, id: 321, lessons: [{ type: 'lesson', id: 444, index: 1 }, { type: 'lesson', id: 555, index: 2 } ] }] }

const result = item.sections.map(({ id, lessons }) => { 
    return ({ section: +id, lessons: lessons.map(({ id }) => id) })
});
console.log('Result:', result);
    
.as-console-wrapper { max-height: 100% !important; }

1 Comment

once small improvement here could be "variable shadowing" with having both sectionId and lessonId as id in the lessons.map callback, but the general idea of course is perfect 💯

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.