Tengo una matriz de objetos en el formato siguiente y me gustaría transformarla en una nueva matriz de objetos utilizando una propiedad como clave. La clave debe ser única. Ver la forma del objeto a continuación
const mockedList = [ { email: 'aaa@example.com', id: '5052', name: 'Java', }, { email: 'bbb@example.com', id: '5053', name: 'Python', }, { email: 'aaa@example.com', id: '5054', name: 'C#', }, { email: 'bbb@example.com', id: '5055', name: 'Javascript', }, ];Me gustaría transformar esto y obtener una matriz de objetos con claves y valores en este formato.
[ { email: 'bbb@example.com', languages: [ { email: 'bbb@example.com', id: '5055', name: 'Javascript', }, { email: 'bbb@example.com', id: '5053', name: 'Python', }, ] }, { email: 'aaa@example.com', languages: [ { email: 'aaa@example.com', id: '5052', name: 'Java', }, { email: 'aaa@example.com', id: '5054', name: 'C#', }, ] } ]He intentado usar map-reduce
const result = mockedList.reduce((r, a) => { r[a.email] = r[a.email] || []; r[a.email].push(a); return r; }, Object.create(null));Pero no obtuve la forma correcta de los datos.
Tu puedes hacer:
const mockedList = [{email: 'aaa@example.com',id: '5052',name: 'Java',},{email: 'bbb@example.com',id: '5053',name: 'Python',},{email: 'aaa@example.com',id: '5054',name: 'C#',},{ email: 'bbb@example.com', id: '5055', name: 'Javascript' },] const mockedListHash = mockedList.reduce((a, c) => { a[c.email] = a[c.email] || { email: c.email, languages: [] } a[c.email].languages.push(c) return a }, {}) const result = Object.values(mockedListHash) console.log(result) En caso de que desee limpiar los correos electrónicos repetidos dentro de los languages :
const mockedList = [{email: 'aaa@example.com',id: '5052',name: 'Java',},{email: 'bbb@example.com',id: '5053',name: 'Python',},{email: 'aaa@example.com',id: '5054',name: 'C#',},{ email: 'bbb@example.com', id: '5055', name: 'Javascript' },] const mockedListHash = mockedList.reduce((a, c) => { a[c.email] = a[c.email] || { email: c.email, languages: [] } a[c.email].languages.push({ id: c.id, name: c.name, }) return a }, {}) const result = Object.values(mockedListHash) console.log(result)Aquí hay otra opción con bucle for simple
// Array const mockedList = [ { email: 'aaa@example.com', id: '5052', name: 'Java' }, { email: 'bbb@example.com', id: '5053', name: 'Python' }, { email: 'aaa@example.com', id: '5054', name: 'C#' }, { email: 'bbb@example.com', id: '5055', name: 'Javascript' } ]; // Set new object const newObj = {}; // Use regular loop for(const el of mockedList) { // Use email as key // If key already exist, add info // to it's languages array if(newObj[el.email]) newObj[el.email].languages.push(el); else newObj[el.email] = { email: el.email, languages: [el] } } // Test console.log(newObj); // If you need just array of objects, // without email as key, then transform it const newArr = Object.keys(newObj).map((key) => newObj[key]); // Test console.log(newArr);