2017-08-24 1 views
-1

J'ai un json avec plusieurs tableaux d'objets.lodash mapper plusieurs tableaux d'objets

{ 
    "results":[{ 
    "id_pk": "1", 
    "bookings": [{ 
     "id": 1, 
     "id": 2, 
    }] 
    },{ 
    "id_pk": "2", 
    "bookings": [{ 
     "id": 3, 
     "id": 4, 
    }] 
    },{ 
    "id_pk": "3", 
    "bookings": [{ 
     "id": 5, 
     "id": 6, 
    }] 
    }] 
} 

et mon but est d'obtenir l'identifiant de chaque "id_pk" en utilisant _.map() de lodash

et mon code ressemble à ceci. Est-ce un format correct pour obtenir l'identifiant?

_.map(results, (r) => _.map(r.bookings, 'id')) 
+0

ça marche? quel résultat obtenez-vous? –

+0

http://imgur.com/a/naZJG ce genre de résultat que je reçois en ce moment –

+0

http://imgur.com/a/k0Ltv mon objectif est comme ceci ou avec 0: 1,2 | 1: 3,4 | 2: 5,6 | les virgules –

Répondre

0

Vous pouvez obtenir toutes les valeurs id en réduisant le tableau extérieur et cartographie tous les id du tableau booking et rejoindre l'id d'un nouvel objet.

var data = { results: [{ id_pk: "1", bookings: [{ id: 1 }, { id: 2 }] }, { id_pk: "2", bookings: [{ id: 3 }, { id: 4 }] }, { id_pk: "3", bookings: [{ id: 5 }, { id: 6 }] }] }, 
 
    ids = data.results.reduce((r, a, i) => (r[i] = a.bookings.map(b => b.id).join(), r), {}); 
 

 
console.log(ids);