繁体   English   中英

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

[英]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和series数组中有更多的对象。 我想创建一个这样的新对象

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

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

我相信最好/最短的事情是使用地图功能,例如:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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