Ri-struttura dell'array JavaScript


16

Ho un array con indirizzi di studenti e genitori.

Per esempio,

  const users = [{
    id: 1,
    name: 'John',
    email: 'johnson@mail.com',
    age: 25,
    parent_address: 'USA',
    relationship:'mother'
  },
  {
    id: 1,
    name: 'John',
    email: 'johnson@mail.com',
    age: 25,
    parent_address: 'Spain',
    relationship:'father'
  },
  {
    id: 2,
    name: 'Mark',
    email: 'mark@mail.com',
    age: 28,
    parent_address: 'France',
    relationship:'father'
  }
];

Sto cercando di riformattare questo per il seguente risultato.

const list = [
{
    id: 1,
    name: 'John',
    email: 'johnson@mail.com',
    age: 25,
    parent: [
        {
            parent_address: 'USA',
            relationship:'mother'
        },{
            parent_address: 'Spain',
            relationship:'father'
        }
    ]
},
{
    id: 2,
    name: 'Mark',
    email: 'mark@mail.com',
    age: 28,
    parent:[
        {
            parent_address: 'France',
            relationship:'father'
        }
    ]
}
];

Finora ho provato nel modo seguente. Non sono sicuro che sia la strada giusta o no.

const duplicateInfo = [];
for (var i = 0; i < user[0].length; i++) {
    var parent = [];
    if (duplicateInfo.indexOf(user[0][i].id) != -1) {
        // Do duplicate stuff
    } else {
        // Do other
    }
    duplicateInfo.push(user[0][i].id);
}

1
Quindi in breve - per facilitare i futuri lettori - si desidera combinare parent_addresse unire relationshipun parentoggetto e unirli quando vengono trovati un nome duplicato e un indirizzo e-mail.
Lewis,

2
Come può essere preso l'indirizzo principale? Quale proprietà dovrebbe essere usata per metterli in relazione? Grazie in anticipo! :)
StepUp

Lo snippet di codice alla fine non corrisponde alla struttura dei dati. Dici const list = []all'inizio, ma in fondo fai scorrere quella lista apparentemente ripetendo user[0]. Il tuo codice di esempio dovrebbe essere coerente.
TKoL

@Lewis si, voglio esattamente come hai menzionato.
kathy

@SteUp, quei valori lo recuperano dal mio db esistente e si uniscono alla tabella degli studenti e dei genitori. Quello che ho solo l'ID dello studente nella tabella padre.
kathy

Risposte:


12

Un approccio sarebbe quello di utilizzare .reduce()un oggetto come accumulatore. Per ogni ID, è possibile memorizzare un oggetto associato con un array parent che è possibile aggiungere nel .reduce()callback ogni volta che si incontra un nuovo oggetto con lo stesso ID. Quindi per ottenere un array di oggetti dal proprio oggetto, è possibile chiamare Object.values()su di esso

Vedi l'esempio seguente:

const users = [{ id: 1, name: 'John', email: 'johnson@mail.com', age: 25, parent_address: 'USA', relationship: 'mother' }, { id: 1, name: 'John', email: 'johnson@mail.com', age: 25, parent_address: 'Spain', relationship: 'father' }, { id: 2, name: 'Mark', email: 'mark@mail.com', age: 28, parent_address: 'France', relationship: 'father' } ];
const res = Object.values(users.reduce((acc, {parent_address, relationship, ...r}) => { // use destructuring assignment to pull out necessary values
  acc[r.id] = acc[r.id] || {...r, parents: []}
  acc[r.id].parents.push({parent_address, relationship}); // short-hand property names allows us to use the variable names as keys
  return acc;
}, {}));

console.log(res);

Dato che hai menzionato la tua conoscenza di JS, potrebbe essere più semplice da capire in un modo più imperativo (vedi i commenti sul codice per i dettagli):

const users = [{ id: 1, name: 'John', email: 'johnson@mail.com', age: 25, parent_address: 'USA', relationship: 'mother' }, { id: 1, name: 'John', email: 'johnson@mail.com', age: 25, parent_address: 'Spain', relationship: 'father' }, { id: 2, name: 'Mark', email: 'mark@mail.com', age: 28, parent_address: 'France', relationship: 'father' } ];

const unique_map = {}; // create an object - store each id as a key, and an object with a parents array as its value
for(let i = 0; i < users.length; i++) { // loop your array object
  const user = users[i]; // get the current object
  const id = user.id; // get the current object/users's id
  
  if(!(id in unique_map)) // check if current user's id is in the the object
    unique_map[id] = { // add the id to the unique_map with an object as its associated value 
      id: id,
      name: user.name,
      email: user.email,
      age: user.age,
      parents: [] // add `parents` array to append to later
    }
    
  unique_map[id].parents.push({ // push the parent into the object's parents array
    parent_address: user.parent_address,
    relationship: user.relationship
  });
}

const result = Object.values(unique_map); // get all values in the unique_map
console.log(result);


Grazie, controllerò i dettagli e sono molto esistito per leggere il tuo codice.
Kathy,

Ooh questo è solido. L'oggetto che distrugge nel reducecallback è carino, ma forse un po 'pesante per un principiante.
TKoL

1
@TKoL grazie, proverò ad aggiungere una versione "più semplice"
Nick Parsons,

1
La versione più semplice sembra fantastica!
TKoL

1
Grazie mille. Ho letto il tuo codice e facile da capire soprattutto sul secondo frammento di codice. Apprezzo anche la risposta degli altri membri. Ancora grazie mille ragazzi.
Kathy,

5

È possibile ridurre l'array e cercare un utente con lo stesso ID e aggiungere le informazioni padre ad esso.

Se l'utente non viene trovato, aggiungere un nuovo utente al set di risultati.

const
    users = [{ id: 1, name: 'John', email: 'johnson@mail.com', age: 25, parent_address: 'USA', relationship: 'mother' }, { id: 1, name: 'John', email: 'johnson@mail.com', age: 25, parent_address: 'Spain', relationship: 'father' }, { id: 2, name: 'Mark', email: 'mark@mail.com', age: 28, parent_address: 'France', relationship: 'father' }],
    grouped = users.reduce((r, { parent_address, relationship, ...user }) => {
        var temp = r.find(q => q.id === user.id );
        if (!temp) r.push(temp = { ...user, parent: []});
        temp.parent.push({ parent_address, relationship });
        return r;
    }, []);

console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }


2

La ristrutturazione di dati come questo è piuttosto comune ed Array.reduce()è progettata per l'attività. È un modo diverso di vedere le cose e ci vuole un po 'per abituarsi, ma dopo aver scritto il codice alcune volte diventa una seconda natura.

reduce() viene chiamato su un array e accetta due parametri:

  1. una funzione che verrà chiamata per ciascun elemento dell'array
  2. il valore iniziale

La tua funzione viene quindi chiamata per ogni elemento con il valore iniziale per la prima esecuzione o il valore restituito dalla chiamata di funzione precedente per ogni esecuzione successiva, lungo l'elemento array, indicizza l'array originale e l'array originale che riducono () è stato chiamato (gli ultimi due sono generalmente ignorati e raramente necessari). Dovrebbe restituire l'oggetto o qualunque cosa tu stia costruendo con l'elemento corrente aggiunto e quel valore restituito viene passato alla chiamata successiva alla tua funzione.

Per cose come questa di solito ho un oggetto per mantenere le chiavi univoche ( idper te), ma vedo che vuoi che venga restituita una matrice. Questa è una riga per mappare l'oggetto e le chiavi su un array ed è più efficiente usare il meccanismo di proprietà dell'oggetto incorporato invece di array.find () per vedere se hai già aggiunto un ID.

const users = [{
    id: 1,
    name: 'John',
    email: 'johnson@mail.com',
    age: 25,
    parent_address: 'USA',
    relationship:'mother'
  },
  {
    id: 1,
    name: 'John',
    email: 'johnson@mail.com',
    age: 25,
    parent_address: 'Spain',
    relationship:'father'
  },
  {
    id: 2,
    name: 'Mark',
    email: 'mark@mail.com',
    age: 28,
    parent_address: 'France',
    relationship:'father'
  }
];

let combined = users.reduce(
  // function called for each element in the array
  (previous, element) => {
    // previous starts out as the empty object we pass as the second argument
    // and will be the return value from this function for every other element
    
    // create an object for the id on our 'previous' object if it doesn't exist,
    // if it does exist we will trust the name, email, and age from the first
    // instance
    previous[element.id] = previous[element.id] || {
      id: element.id,
      name: element.name,
      age: element.age,
      parents: []
    };
    
    // now add parent
    previous[element.id].parents.push({
      parent_address: element.parent_address,
      relationship: element.relationship
    });
    
    // return our updated object, which will be passed to the next call
    // and eventually returned
    return previous;
  },
  {} // initial value is an empty object, no ids yet
);

// transform object into array with elements in order by key
let list = Object.keys(combined).sort().map(key => combined[key]);

console.dir(list);


1

È necessario ripetere due volte utilizzando il metodo corrente. La complessità è O (n ^ 2). (per Loop + indexOf)

Un modo migliore è indicizzare l'array e utilizzare la chiave dell'array per il rilevamento e la ricerca della duplicazione.

Per esempio:

const map = {};
users.forEach(user => {
    // Will return undefined if not exist
    let existing = map[user.id];
    if (!existing) {
        // If not exist, create new
        existing = {
            id: user.id,
            ...
            parents: [ {parent_address: user.parent_address, relationship: user.relationship ]
        }
    } else {
        // Otherwise, update only parents field
        // You can add other logic here, for example update fields if duplication is detected.
        existing.parents.push({parent_address: user.parent_address, relationship: user.relationship ]
        });
    }
    map[user.id] = existing;
})
// Convert the object to array
const list = map.values();

Grazie, controllerò i dettagli e sono molto esistito per leggere il tuo codice.
Kathy,

1
const users = [{
    id: 1,
    name: 'John',
    email: 'johnson@mail.com',
    age: 25,
    parent_address: 'USA',
    relationship:'mother'
  },
  {
    id: 1,
    name: 'John',
    email: 'johnson@mail.com',
    age: 25,
    parent_address: 'Spain',
    relationship:'father'
  },
  {
    id: 2,
    name: 'Mark',
    email: 'mark@mail.com',
    age: 28,
    parent_address: 'France',
    relationship:'father'
  }
];
const updatedUsers = users.map(user => {
    return {
    id: user.id,
    name: user.name,
    email: user.email,
    age: user.age,
    parent: [{
        relationship: user.relationship,
        parent_address: user.parent_address,
    }]
}
})

const list = updatedUsers.reduce((acc, user) => {
    const findIndex = acc.findIndex(eachUser => eachUser.id === user.id && eachUser.email === user.email);
    if (findIndex < 0) {
        acc.push(user);
        return acc;
    } else {
    acc[findIndex].parent.push(user.parent);
    return acc; 
    }
}, []);
console.log(list)

1
Una spiegazione sarebbe in ordine. Ad esempio, cosa hai cambiato? E perché?
Peter Mortensen,

1

Puoi usare la Mapraccolta per conservare oggetti unici e semplicemente popolarli usando filter:

const unique = new Map(users.map(u=> 
    [u.id, {...u, parent: [...users.filter(f => f.id == u.id)]}]));

console.log(Array.from(unique, ([k, v])=> v)
    .map(s => ( { id: s.id, name: s.name, email: s.email, age:s.age, parent:s.parent })));

const users = [
  {
    id: 1,
    name: 'John',
    email: 'johnson@mail.com',
    age: 25,
    parent_address: 'USA',
    relationship: 'mother'
  },
  {
    id: 1,
    name: 'John',
    email: 'johnson@mail.com',
    age: 25,
    parent_address: 'Spain',
    relationship: 'father'
  },
  {
    id: 2,
    name: 'Mark',
    email: 'mark@mail.com',
    age: 28,
    parent_address: 'France',
    relationship: 'father'
  }
];

const unique = new Map(users.map(u=> 
    [u.id, {...u, parent: [...users.filter(f => f.id == u.id)]}]));

console.log(Array.from(unique, ([k, v])=> v).map(s => ( 
    { id: s.id, name: s.name, email: s.email, age:s.age, parent:s.parent })));


0

 const users = [{
    id: 1,
    name: 'John',
    email: 'johnson@mail.com',
    age: 25,
    parent_address: 'USA',
    relationship:'mother'
  },
  {
    id: 1,
    name: 'John',
    email: 'johnson@mail.com',
    age: 25,
    parent_address: 'Spain',
    relationship:'father'
  },
  {
    id: 2,
    name: 'Mark',
    email: 'mark@mail.com',
    age: 28,
    parent_address: 'France',
    relationship:'father'
  }
];
ids = new Map()
for (const user of users) {
  var newuser;
  if (ids.has(user.id)) {
    newuser = ids.get(user.id);
  } else {
    newuser = {};
    newuser.id = user.id;
    newuser.name = user.name;
    newuser.email = user.email;
    newuser.age = user.age;
    newuser.parent = [];
  }
  relationship = {};
  relationship.parent_address = user.parent_address;
  relationship.relationship = user.relationship;
  newuser.parent.push(relationship)
  ids.set(user.id, newuser);
}
list = [ ...ids.values() ];
list.forEach((u) => {
  console.log(JSON.stringify(u));
});

Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.