简体   繁体   中英

How to group objects with specific key in javaScript

I want to do a grouping for JavaScript object as age.My JSON is

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.

Use Array#reduce to group the objects. Because there can multiple people with the same age, collect them into an array under the age property:

 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:

 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.
Add underscore js first

<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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM