JS 有趣的小题目
到处看文章,晃到的一个小题目。
看似简单,但还是耗了一些时间才想出解法。
// 原始资料const data = [ { id: 1, content: 'hello', category: 'HTML' }, { id: 1, content: 'hello', category: 'JS' }, { id: 1, content: 'hello', category: 'CSS' }, { id: 2, content: 'hi', category: 'CSS' },]// 目标const target = [ { id: 1, content: 'hello', category: 'HTML,JS,CSS' }, { id: 2, content: 'hi', category: 'CSS' },]
个人解法
const newData = [] data.forEach((el) => { // 判断有该id的object 是否存在于 新的阵列中 // 无则加入,有则找到该物件 并将 category加入其后 if (!newData.find(elem => elem.id === el.id)) { newData.push(el) } else { const index = newData.findIndex(elem => elem.id === el.id) newData[index].category += `,${el.category}` } }) console.dir(newData)