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 consoleconsole.log(Array.from(map.values())) // The siteIds in array form一旦将它们放在map对象中,就可以像map.get(13)一样通过siteID轻松访问组,您将获得siteID为13的分组项的数组.您还可以始终通过 Map.keys()方法.Everyone, this is my Array Structure let data = [ {"name": "ragupathi", "siteID": 10}, {"name": "abi","siteID": 13}, {"name": "mahesh", "siteID": 12},]i want group data based on siteIDso I am using groupBy siteIDthe current output is :{ "10": [ { "name": "ragupathi", "siteID": 10 } ], "12": [ { "name": "mahesh", "siteID": 12 } ], "13": [ { "name": "abi", "siteID": 13 } ]}But I am Expecting output name in ASC order { "13": [ { "name": "abi", "siteID": 13 } ], "10": [ { "name": "mahesh", "siteID": 12 } ], "12": [ { "name": "ragupathi", "siteID": 10 } ],}GroupBy SiteIDGrouped Output based on properties of Object Name 解决方案 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: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 consoleconsole.log(Array.from(map.values())) // The siteIds in array formOnce you have them in the 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.You can also always get the order in which you have stored the keys in the map via the Map.keys() method. 这篇关于更改_.groupBy()结果数据的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
09-09 14:04