[英]Splitting an jsonarray based on key with lodash underscore
I am trying to get the unique items in each column of a json array. 我试图获取json数组的每一列中的唯一项。 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} ];
var items = [{“ name”:“ Type 1”,“ id”:13},{“ name”:“ Type 2”,“ id”:14},{“ name”:“ Type 3”,“ id “:14},{” name“:”类型3“,” id“:13},{” name“:”类型2“,” id“:12},{” name“:”类型3“,” id“:12}];
into 进入
[{"Type 1","Type 2","Type 3"},{12,13,14}]
[{“ 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/ 小提琴: 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). 但这对于我的用例而言似乎是无效的解决方案,因为我的真实数据集要大得多(100000个元素,每个元素中有6个键)。 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.
我理想的方法是:1.根据键拆分数组。 2. Then find the unique in the each of the split.
2.然后在每个拆分中找到唯一性。 3. Join the results.
3.加入结果。
Thanks. 谢谢。
You can use a combination _.values()
to convert the object to array, _.zip()
to transpose the arrays, and then map them with _.uniq()
: 可以使用
_.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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.