简体   繁体   中英

Splitting an jsonarray based on key with lodash underscore

I am trying to get the unique items in each column of a json array. I want to convert this :

var items = [ {"name": "Type 1","id": 13}, {"name": "Type 2","id": 14}, {"name": "Type 3","id": 14}, {"name": "Type 3","id": 13}, {"name": "Type 2","id": 12}, {"name": "Type 3","id": 12} ];

into

[{"Type 1","Type 2","Type 3"},{12,13,14}]

This is what I tried :

var uniq1 = _.map(_.uniqBy(items, 'id'), 'id');
var uniq2 =_.map(_.uniqBy(items, 'name'), 'name')
console.log(uniq1,uniq2)

Fiddle : https://jsfiddle.net/yogeshwaran/5ntfzss1/

But this seems to be an inefficient solution for my use case as my real dataset is much bigger (100000 elements with 6 keys in each element). Is there a way to get all unique values for each of the keys. I do not want to iterate over the entire set each and every time. My ideal approach would be : 1. Split the array based on keys. 2. Then find the unique in the each of the split. 3. Join the results.

Thanks.

You can use a combination _.values() to convert the object to array, _.zip() to transpose the arrays, and then map them with _.uniq() :

 var items = [ {"name": "Type 1","id": 13, "position": "manager"}, {"name": "Type 2","id": 14, "position": "manager"}, {"name": "Type 3","id": 14, "position": "manager"}, {"name": "Type 3","id": 13, "position": "worker"}, {"name": "Type 2","id": 12, "position": "worker"}, {"name": "Type 3","id": 12, "position": "manager"} ]; var result = _.zip.apply(_, items.map(_.values)).map(_.uniq); console.log(result); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.6/lodash.min.js"></script> 

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