Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
114
rated 0 times [  115] [ 1]  / answers: 1 / hits: 16183  / 9 Years ago, wed, march 4, 2015, 12:00:00

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



Returned



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}


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 :)



Update



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


More From » json

 Answers
16

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



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>




[#67571] Monday, March 2, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
felix

Total Points: 47
Total Questions: 91
Total Answers: 110

Location: Angola
Member since Tue, May 5, 2020
4 Years ago
;