简体   繁体   中英

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


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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM