I have two objects. Their structure looks a bit like this:
{
education: [\"school\", \"institute\"],
courses: [\"HTML\", \"JS\", \"CSS\"],
Computer: {
Edit: didn't notice that merge
changes the first argument... changed the code, but it still would cause obj2 to change. You can add _.cloneDeep(obj2)
which should take care of that, but by then my solution doesn't seem as elegant. Updated the demo with cloneDeep
as well.
Edit2: Since JSON.stringify
requires the order of object properties to be the same in the objects you compare, you could instead use something like Object comparison in JavaScript. However, in the demo you can see that it works, so I would say there is a good chance that for your case, using _.merge
with JSON.stringify
is reliable.
With lo-dash, you can use _.merge
and check whether the result is the same as the larger object.
function(obj1, obj2) {
var obj3 =_.merge(_.cloneDeep(obj2), obj1);
return JSON.stringify(obj3) === JSON.stringify(obj1);
}
demo
Of course, another option would be to iterate over the entire object with vanilla JS.