使用另一个对象的值创建一个对象数组

Create an array of objects with values from another object

我有一个看起来像这样的对象

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

假设sections和lessons数组中的对象较多。我想像这样创建一个新对象

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

我试过这个循环,但这只是推送索引而不是课程的 ID


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

我怎样才能正确地做到这一点,并且最好考虑到良好的性能?

我相信 best/shortest 事情是使用地图功能,例如:

const result2 = item.sections.map(({id, lessons}) => ({
  id, 
  lessons: lessons.map(({id: lessionId}) => lessionId)
}))

我建议使用 Array.map() 将项目部分转换为所需的结果。

我们会将每个部分转换为一个对象,该对象具有 section 值和 lessons 数组。

为了创建课程数组,我们再次使用 Array.map() 将每个课程映射到课程 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; }