【问题标题】:Splitting an jsonarray based on key with lodash underscore使用 lodash 下划线根据键拆分 jsonarray
【发布时间】:2016-05-12 19:17:20
【问题描述】:

我正在尝试获取 json 数组的每一列中的唯一项。我想转换这个:

var items = [ {"name": "Type 1","id": 13}, {"name": "Type 2","id": 14},{“名称”:“类型 3”,“id”:14},{“名称”:“类型 3”,“id”:13}, {"name": "Type 2","id": 12}, {"name": "Type 3","id": 12} ];

进入

[{"Type 1","Type 2","Type 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/

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

谢谢。

【问题讨论】:

  • 你可以使用 vanilla js 或者 new js Sets(注意浏览器支持)来提高 ir 的效率
  • 您是在浏览器中为 Web 应用程序执行此操作还是仅用于处理 JSON 数据?如果是后者,我建议使用jq 来处理大型 JSON 数据集,并且有很多不错的 helper functions

标签: javascript jquery underscore.js lodash text-processing


【解决方案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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-04
    • 1970-01-01
    • 1970-01-01
    • 2013-03-20
    相关资源
    最近更新 更多