如果它具有相同的id,我想将值合并到数组。我有一个像这样的对象数组。[ { id: 'Tony', type: 'hero', favorite: 'Rosie', }, { id: 'Jane', type: 'human', favorite: null, }, { id: 'Tony', type: 'hero', favorite: 'Lisa', }, { id: 'Steve', type: 'hero', favorite: 'Jennie', }, { id: 'Tony', type: 'hero', favorite: 'Jisoo', },]我想将键favorite从字符串合并到数组。我想要像这样的输出[ { id: 'Tony', type: 'hero', favorite: ['Rosie', 'Lisa', 'Jisoo'], }, { id: 'Jane', type: 'human', favorite: null, }, { id: 'Steve', type: 'hero', favorite: ['Jennie'], } 我尝试编写这样的代码:(来自:对象数组中的相似键)var obj = [ { id: 'Tony', type: 'hero', favorite: 'Rosie', }, { id: 'Jane', type: 'human', favorite: null, }, { id: 'Tony', type: 'hero', favorite: 'Lisa', }, { id: 'Steve', type: 'hero', favorite: 'Jennie', }, { id: 'Tony', type: 'hero', favorite: 'Jisoo', }, ]; var holder = {}; const ar = [] obj.forEach(function (d) { if (holder.hasOwnProperty(d.id)) { holder[d.id] = ar.push(holder[d.id] + d.favorite); } else { holder[d.id] = d.favorite; } }); var obj2 = []; for (var prop in holder) { obj2.push({ name: prop, favorite: holder[prop] }); } console.log(obj2);但是输出是[ { name: 'Tony', favorite: 2 }, { name: 'Jane', favorite: null }, { name: 'Steve', favorite: 'Jennie' } ]我怎样才能做到这一点 ?
添加回答
举报
0/150
提交
取消