Reputation:
I have an array that looks like this one (it has more objects, but the structure is the same):
[
{
especiality: "surgery",
users: [
{
id: "182",
country: "Colombia",
province: "Bogota",
telephone: "211112212",
neighbourhood: "La Santa"
region: "South",
},
{
id: "182",
country: "Venezuela",
province: "Caracas",
telephone: "322323333",
region: "North",
},
{
id: "183",
country: "Brasil",
telephone: "23232333",
neighbourhood: "Santos"
region: "South",
},
]
},
I want the addresses, if the ID is the same, to compose one single array (I need to map these elements). The outlook should look like this one:
user: [{id: 182, locations[(if they exist)
country: "Colombia",
province: "Bogota",
telephone: "211112212",
neighbourhood: "La Santa"
region: "South"], [country: "Venezuela",
province: "Caracas",
telephone: "322323333",
region: "North"],}]
I´m currently trying this, but it´s not working at all:
getGroups = test => {
_.chain(test)
.groupBy("id")
.toPairs()
.map(item => _.zipObject(["id", "country", "province", "neighbourhood", "region"], item))
.value();
return test
}
What am I doing wrong and how can I account for values that may not be available in all objects?
Upvotes: 1
Views: 106
Reputation: 191996
After grouping the items by the id
, map the groups, and create an object with the id
, and the items of the group as locations
. Map the locations, and use _.omit()
to remove the id
from them.
I'm not sure about how you want to handle the outer array. I've used _.flatMap()
to get a single array of users, but there's a commented option if you need to maintain the original structure.
getGroups = test =>
_(test)
.groupBy("id")
.map((locations, id) => ({
id,
locations: _.map(locations, l => _.omit(l, 'id'))
}))
.value();
const data = [{"especiality":"surgery","users":[{"id":"182","country":"Colombia","province":"Bogota","telephone":"211112212","neighbourhood":"La Santa","region":"South"},{"id":"182","country":"Venezuela","province":"Caracas","telephone":"322323333","region":"North"},{"id":"183","country":"Brasil","telephone":"23232333","neighbourhood":"Santos","region":"South"}]}];
const result = _.flatMap(data, ({ users }) => getGroups(users));
/** maintains the original structure
const result = _.map(data, ({ users, ...rest }) => ({
...rest,
users: getGroups(users)
}));
**/
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>
Upvotes: 1