简体   繁体   中英

How to use groupBy on object in Javascript?

I have an object as below:

obj = {
 'fruita' : 'eat',
 'fruitb' : 'eat',
 'fruitc' : 'throw',
 'fruitd' : 'throw'
}

output = {
 'eat' : ['fruita','fruitb'],
 'throw' : ['fruitc','fruitd']
}

How to apply _.groupBy in order to get the list of eat and throw fruits seperately?

We can turn our object to an array of key-value pairs:

var keyValues = Object.keys(obj).map(key => ({ key, value: obj[key] }));

And then we can perform a reduce to construct our object:

var values = keyValues.reduce((acc, kv) => {
    if (typeof acc[kv.value] === 'undefined') {
        acc[kv.value] = [];
    }

    acc[kv.value].push(kv.key);
    return acc;
}, {});

No lodash necessary!

You could use a for..in loop to set properties of output object to values of obj , push obj properties to items within array at output

 var obj = { 'fruita' : 'eat', 'fruitb' : 'eat', 'fruitc' : 'throw', 'fruitd' : 'throw' } var output = {}; for (var prop in obj) { if (!output[obj[prop]]) { output[obj[prop]] = []; output[obj[prop]].push(prop) } else { output[obj[prop]].push(prop) } } console.log(output) 

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