Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create an array of objects with values from another object

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel


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?

>Solution :

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)
}))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading