更改_.groupBy()结果数据的顺序 [英] Change the Order of _.groupBy() result Data
问题描述
每个人,这是我的数组结构
let data = [
{"name": "ragupathi", "siteID": 10},
{"name": "abi","siteID": 13},
{"name": "mahesh", "siteID": 12},
]
我想要基于siteID的组数据 所以我在用groupBy siteID
让样本= _.groupBy(data,'siteID');
当前输出为:
{
"10": [
{
"name": "ragupathi",
"siteID": 10
}
],
"12": [
{
"name": "mahesh",
"siteID": 12
}
],
"13": [
{
"name": "abi",
"siteID": 13
}
]
}
但是我希望输出名称按ASC顺序
{
"13": [
{
"name": "abi",
"siteID": 13
}
],
"10": [
{
"name": "mahesh",
"siteID": 12
}
],
"12": [
{
"name": "ragupathi",
"siteID": 10
}
],
}
- 通过SiteID分组
- 基于对象名称属性的分组输出
由于不能保证道具的顺序,您必须使用 Array.sort , Array.forEach 和地图像这样:>
let data = [{"name": "ragupathi", "siteID": 10},{"name": "abi", "siteID": 13},{"name": "abi","siteID": 13},{"name": "mahesh", "siteID": 12},{"name": "abi", "siteID": 13},{"name": "abi", "siteID": 13},{"name": "ragupathi", "siteID": 10}],
map = new Map()
data
.sort((a,b) => b.siteID - a.siteID)
.forEach(x => map.set(x.siteID, [...(map.get(x.siteID) || []), x] || [x]))
console.log(map) // The map object output in your browser console
console.log(Array.from(map.values())) // The siteIds in array form
一旦将它们放在map
对象中,就可以像map.get(13)
一样通过siteID
轻松访问组,您将获得siteID为13的分组项的数组.
您还可以始终通过 i want group data based on siteID
so I am using groupBy siteID let sample = _.groupBy(data,'siteID'); the current output is : But I am Expecting output name in ASC order
Since order of the props is not guaranteed you have to utilize Map or other methods to get the sorting and the output you need. You can use Array.sort, Array.forEach and Map like this:
Once you have them in the You can also always get the order in which you have stored the keys in the map via the Map.keys() method. 这篇关于更改_.groupBy()结果数据的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
{
"10": [
{
"name": "ragupathi",
"siteID": 10
}
],
"12": [
{
"name": "mahesh",
"siteID": 12
}
],
"13": [
{
"name": "abi",
"siteID": 13
}
]
}
{
"13": [
{
"name": "abi",
"siteID": 13
}
],
"10": [
{
"name": "mahesh",
"siteID": 12
}
],
"12": [
{
"name": "ragupathi",
"siteID": 10
}
],
}
let data = [{"name": "ragupathi", "siteID": 10},{"name": "abi", "siteID": 13},{"name": "abi","siteID": 13},{"name": "mahesh", "siteID": 12},{"name": "abi", "siteID": 13},{"name": "abi", "siteID": 13},{"name": "ragupathi", "siteID": 10}],
map = new Map()
data
.sort((a,b) => b.siteID - a.siteID)
.forEach(x => map.set(x.siteID, [...(map.get(x.siteID) || []), x] || [x]))
console.log(map) // The map object output in your browser console
console.log(Array.from(map.values())) // The siteIds in array form
map
object then you can access the groups easily by siteID
like map.get(13)
and you will get the array of the grouped items for the siteID of 13.