Unisci gli array in un array dopo aver filtrato


14

Ho una serie di oggetti, dove prendo solo posizioni array. Il mio obiettivo è unire questi array di posizioni in un array, tuttavia non riesco a farlo e ottengo un array vuoto. Ecco come lo faccio:

let results = [{
    id: '1',
    locations: ['aaaa', 'bbbbbb', 'cccccc']
  },
  {
    id: '2',
    locations: []
  },
  {
    id: '3',
    locations: ['ddd', 'aaadsad', 'sefd']
  },
  {
    id: '4',
    locations: ['ffff', 'eeee', 'sfdsfsd']
  },
];
const locationIds = [].concat.apply([], ...results.filter(s => s.locations && s.locations.length > 0).map(({
  locations
}) => ({
  locations
})));

console.log(locationIds);

cosa sto facendo di sbagliato qui? Il risultato dovrebbe essere ['aaaa', 'bbbbbb', 'cccccc', 'ddd', 'aaadsad', 'sefd', 'ffff', 'eeee', 'sfdsfsd'];

Risposte:


9

Non hai bisogno di filterqui. Basta usare il mapmetodo passando una funzione fornita di callback che viene applicata per ogni elemento dell'array.

let results = [{ id: '1', locations: ['aaaa', 'bbbbbb', 'cccccc'] }, { id: '2', locations: [] }, { id: '3', locations: ['ddd', 'aaadsad', 'sefd'] }, { id: '4', locations: ['ffff', 'eeee', 'sfdsfsd'] }, ];

const locationIds = [].concat(...results.map(s => s.locations));

console.log(locationIds);


1
@utente122222, prego! È possibile creare la propria implementazione di flatMapcome qui: stackoverflow.com/questions/39837678/…
Mihai Alexandru-Ionut

7

Puoi provare con flatMap():

Il flatMap()metodo prima mappa ogni elemento usando una funzione di mappatura, quindi appiattisce il risultato in un nuovo array. È identico a un map()seguito da uno flat()di profondità 1 , ma flatMap()è spesso abbastanza utile, poiché la fusione di entrambi in un metodo è leggermente più efficiente.

let results = [{
    id: '1',
    locations: ['aaaa', 'bbbbbb', 'cccccc']
  },
  {
    id: '2',
    locations: []
  },
  {
    id: '3',
    locations: ['ddd', 'aaadsad', 'sefd']
  },
  {
    id: '4',
    locations: ['ffff', 'eeee', 'sfdsfsd']
  },
];
const locationIds = results.flatMap(i => i.locations);
console.log(locationIds);


6

Si potrebbe prendere un Array#flatMapcon la proprietà desiderata. Se la proprietà non viene fornita, aggiungere un array predefinito || [].

let results = [{ id: '1', locations: ['aaaa', 'bbbbbb', 'cccccc'] }, { id: '2', locations: [] }, { id: '3', locations: ['ddd', 'aaadsad', 'sefd'] }, { id: '4', locations: ['ffff', 'eeee', 'sfdsfsd'] }],
    locationIds = results.flatMap(({ locations }) => locations);

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


2
È utile menzionare .flatMap non funziona in Edge e IE senza polyfill.
Zydnar,

3

Può anche risolvere usando la funzione Riduci da Array.prototype.

var newResults = results.reduce(function(acc, curr) {
    return acc.concat(curr.locations)
  },[]
)

spero che sia di aiuto


2

Ho speso troppo tempo per non pubblicare la mia soluzione - puzzle interessante per me, anche se le altre risposte sono senza dubbio più performanti e leggibili. Utilizza lo stesso tipo di strategia del tuo post originale, che potrebbe aiutarti a sottolineare dove è andato storto.

const locationIds = [].concat
                    .apply([], results.filter(result => 
                    result.locations && result.locations.length > 0)
                    .map(result => { return result.locations }));
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.