2016-05-12 33 views
0

我想在json数组的每一列中获得独特的项目。我想转换此:基于密钥与lodash下划线分裂一个jsonarray

VAR项目= [{ “名”: “1型”, “ID”:13},{ “名”: “2型”, “ID”: 14} ,{“name”:“Type 3”,“id”:14},{“name”:“Type 3”,“id”:13}, {“name”:“Type 2”,“id” 12},{“name”:“Type 3”,“id”:12}];

[{ “类型1”, “2型”, “类型3”},{12,13,14}]

这是我试图:

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

小提琴:https://jsfiddle.net/yogeshwaran/5ntfzss1/

但这似乎ŧ o因为我的实际数据集要大得多(每个元素有6个键的100000个元素),所以对我的用例来说是一个效率低下的解决方案。有没有办法为每个键获取所有唯一值。我不想每次遍历整个集合。我的理想方法是: 1.根据键分割阵列。 2.然后找到每个拆分中的唯一。 3.加入结果。

谢谢。

+0

既可以使用香草JS或新js集(注意浏览器支持)使ir更有效 – juvian

+0

您是在浏览器中为Web应用程序执行此操作还是仅用于处理JSON数据?如果是后者,我推荐使用'jq'来处理大的JSON数据集,并且有很多不错的[helper functions](https://stedolan.github.io/jq/manual/#TypesandValues)。 – aug

回答

1

可以使用组合_.values()到对象转换为阵列,_.zip()转置阵列,然后用_.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>