我想将JavaScript对象分组为age.My JSON是
var jsonObj=[{"name":"john","age":23},{"name":"mark","age":25},{"name":"jeni","age":21}]`
我想成为这里的小组结果。
[23:{"name":"john","age":23},25:{"name":"mark","age":25},21:{"name":"jeni","age":21}]
请帮助我获得结果,我尝试map
和filter
,但没有得到结果。
答案 0 :(得分:6)
使用Array#reduce对对象进行分组。因为可以有多个年龄相同的人,所以将他们收集到年龄属性下的数组中:
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);
或花哨的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);
答案 1 :(得分:3)
您可以将哈希表作为结果。然后循环并为新键创建新数组。后来推动对象。
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; }
答案 2 :(得分:1)
您可以使用underscore js来解决此问题。
首先添加下划线js
<script src='https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore.js' ></script>
然后您只需获得结果。<登记/>
var result=_.indexBy(jsonObj, 'age');
答案 3 :(得分:0)
你可以尝试一下:
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)