Lodash difference between objects
Attempt at answering http://stackoverflow.com/questions/30703837
by chridam
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.9.3/lodash.js"></script>
JavaScript
function fn(obj, key) {
if (_.has(obj, key)) // or just (key in obj)
return [obj];
// elegant:
return _.flatten(_.map(obj, function(v) {
return typeof v == "object" ? fn(v, key) : [];
}), true);
// or efficient:
var res = [];
_.forEach(obj, function(v) {
if (typeof v == "object" && (v = fn(v, key)).length)
res.push.apply(res, v);
});
return res;
}
var a = {
social: {
username: "JSmith"
},
general: {
color: "red"
}
};
var b = {
social: {
username: "JSmith"
},
general: {
color: "blue"
}
};
console.log(JSON.stringify(_.pluck(a, "color")));
var a1 = _.pluck(a, "color");
var b1 =_.pluck(b, "color");
console.log(JSON.stringify(a1));
console.log(JSON.stringify(b1));
var intersection = _.intersection(a1, b1);
console.log(JSON.stringify(intersection)); // ['c']
var diff = _.difference(a1, b1); // ['a', 'b']
console.log(JSON.stringify(diff));
/*
var intersection = _.intersection(_.values(a), _.values(b));
console.log(JSON.stringify(intersection)); // ['c']
var diff = _.difference(_.values(a), _.values(b)); // ['a', 'b']
console.log(JSON.stringify(diff));
*/