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>