我有一个看起来像这个的数组(它有更多的对象,但结构是一样的):
[
{
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",
},
]
},
我希望地址(如果 ID 相同)组成一个数组(我需要映射这些元素)。前景应该是这样的:
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"],}]
我目前正在尝试这个,但它根本不起作用:
getGroups = test => {
_.chain(test)
.groupBy("id")
.toPairs()
.map(item => _.zipObject(["id", "country", "province", "neighbourhood", "region"], item))
.value();
return test
}
我哪里做错了,我该如何解释并非所有对象都可用的值?
最佳答案
根据id
对项目进行分组后,映射组,并创建一个具有id
的对象,并将组中的项目作为locations
。映射位置,并使用 _.omit()
从中删除 id
。
我不确定您想如何处理外部数组。我使用 _.flatMap()
来获取单个用户数组,但如果您需要维护原始结构,则有一个注释选项。
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>
关于javascript - 使用 lodash : not working 对对象数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55727763/