[英]How to group objects with specific key in javaScript
I want to do a grouping for JavaScript object as age.My JSON is 我想按年龄对JavaScript对象进行分组。我的JSON是
var jsonObj=[{"name":"john","age":23},{"name":"mark","age":25},{"name":"jeni","age":21}]`
I want to be the group result like here. 我想成为这里的小组成绩。
[23:{"name":"john","age":23},25:{"name":"mark","age":25},21:{"name":"jeni","age":21}]
Please help me to get a result, I try with map
and filter
but did not get the result. 请帮助我获得结果,我尝试使用
map
和filter
,但未获得结果。
Use Array#reduce to group the objects. 使用Array#reduce对对象进行分组。 Because there can multiple people with the same age, collect them into an array under the age property:
因为可以有多个相同年龄的人,所以将他们收集到age属性下的数组中:
var jsonObj=[{"name":"john","age":23},{"name":"mark","age":25},{"name":"poll","age":23},{"name":"jeni","age":21}]; var result = jsonObj.reduce(function(r, o) { r[o.age] || (r[o.age] = []); // if the age key doesn't exist, set it to be an array r[o.age].push(o); // push the object into the array return r; }, {}); console.log(result);
Or the fancy ES6 one liner version: 或花哨的ES6一线版:
var jsonObj=[{"name":"john","age":23},{"name":"mark","age":25},{"name":"poll","age":23},{"name":"jeni","age":21}]; var result = jsonObj.reduce((r, o) => ((r[o.age] || (r[o.age] = [])).push(o), r), {}); console.log(result);
You could take the hash table as result. 您可以将哈希表作为结果。 Then loop and create new arrays for new keys.
然后循环并为新键创建新数组。 Later push the object.
以后推对象。
var data = [{ name: "john", age: 23 }, { name: "mark", age: 25 }, { name: "poll", age: 23 }, { name: "jeni", age: 21 }], result = {}; data.forEach(o => (result[o.age] = result[o.age] || []).push(o)); console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can use underscore js to solve this problem. 您可以使用下划线js解决此问题。
Add underscore js first 首先添加下划线js
<script src='https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore.js' ></script>
then you can simply get the result. 那么您可以简单地得到结果。
var result=_.indexBy(jsonObj, 'age');
You can try it : 你可以试试 :
var jsonObj = [{ "name": "john", "age": 23 }, { "name": "mark", "age": 25 }, { "name": "poll", "age": 23 }, { "name": "jeni", "age": 21 }];
let result = {};
jsonObj.forEach(item => {
if(result.hasOwnProperty(item.age)) {
let arr = [];
if(Array.isArray(result[item.age])) {
result[item.age].push(item);
} else {
result[item.age] = [result[item.age], item];
}
} else {
result[item.age] = item;
}
});
console.log(result)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.