Antes
const array = [ { group: '1', tag: ['sins'] }, { group: '1', tag: ['sun'] }, { group: '2', tag: ['red'] }, { group: '2', tag: ['blue'] }, { group: '2', tag: ['black'] }, ];Después
const array = [ { group: '1', tag: ['sins', 'sun'] }, { group: '2', tag: ['red', 'blue', 'black'] }, ];Quiero cambiarlo como el acorde de arriba. Quiero que alguien cree un acorde genial.
Puede convertir la matriz en un objeto usando reduce y convertirlo de nuevo en una matriz.
const array = Object.entries([ { group: '1', tag: ['sins'] }, { group: '1', tag: ['sun'] }, { group: '2', tag: ['red'] }, { group: '2', tag: ['blue'] }, { group: '2', tag: ['black'] }, ].reduce((acc, { group, tag }) => ({ ...acc, [group]: acc[group] ? acc[group].concat(tag) : tag}), {})).map(([group, tag]) => ({ group, tag })); console.log(array);Lea los documentos para la matriz de javascript. https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Array
usted tiene varios métodos para resolver su problema.
const array = [ { group: '1', tag: ['sins'] }, { group: '1', tag: ['sun'] }, { group: '2', tag: ['red'] }, { group: '2', tag: ['blue'] }, { group: '2', tag: ['black'] }, ]; // using reduce to create dictionary and taking group value as key: let groupDicionry = array.reduce((dic, obj) => { // create object if already not in dictionary if(!dic[obj.group]) { dic[obj.group] = { group: obj.group, tag: [] }; }; dic[obj.group].tag.push(obj.tag[0]); return dic }, {}); let result = Object.values(groupDicionry); console.log(result);