lodash/下划线;比较两个对象并删除重复项 [英] lodash/underscore; compare two objects and remove duplicates

查看:284
本文介绍了lodash/下划线;比较两个对象并删除重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如下图所示,我有一些返回的json data,其中包含三个对象;每个都包含一个客户ID =>数据.

As you can see in the image below, I have some returned json data with three objects; each contains a clients id => data.

exact_match : {104}
match_4 :  {104, 103}
match_2 :  {104, 103, 68}

如何基于以前的对象修剪"或删除重复的对象?像这样:

How can I "trim" or remove the duplicate objects based on previous ones? something like:

exact_match : {104}
match_4 :  {103}
match_2 :  {68}

我尝试了 _.difference ,但是没有用(也许是因为它是数组而不是对象? ):

I tried _.difference but did not work (Maybe because it is for arrays not objects?):

var exact_match = data.exact_match,
    match_four_digits = _.difference(data.match_4, data.exact_match),
    match_two_digits = _.difference(data.match_2, data.exact_match, data.match_4),

任何帮助将不胜感激:)

Any help would be appreciated :)

更新

我需要返回的值具有相同的对象数据,而不是新的数组:)

I need that the returned value has the same object data instead of a new array :)

推荐答案

感谢大家的回答,非常感谢您的宝贵时间.

Thanks guys for the answers, I really appreciate your time.

我进一步搜索,发现Lodash开发人员提供的此帖子我想出了这个片段;

I searched further and found this post by Lodash developer that helped me came up with this snippet;

var data = {
  exact_match: {
    104: {
      supplier_id: 104
    }
  },
  match_four_digits: {
    104: {
      supplier_id: 104
    },
    68: {
      supplier_id: 68
    }
  },
  match_two_digits: {
    104: {
      supplier_id: 104
    },
    68: {
      supplier_id: 68
    },
    103: {
      supplier_id: 103
    },
    999: {
      supplier_id: 999
    }
  }
};

var arr_match_four_digits = _.difference(_.keys(data.match_four_digits), _.keys(data.exact_match));
var arr_match_two_digits = _.difference(_.keys(data.match_two_digits), _.keys(data.match_four_digits), _.keys(data.exact_match));



$('#output1').html(JSON.stringify(data));
$('#output2').html(JSON.stringify(_.pick(data.match_four_digits, arr_match_four_digits)));
$('#output3').html(JSON.stringify(_.pick(data.match_two_digits, arr_match_two_digits)));

<script src="https://cdn.rawgit.com/lodash/lodash/3.3.1/lodash.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

data
<pre><code><div id="output1"></div></code></pre>
arr_match_four_digits
<pre><code><div id="output2"></div></code></pre>
match_two_digits
<pre><code><div id="output3"></div></code></pre>

这篇关于lodash/下划线;比较两个对象并删除重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆