Suppose we have 2 objects:
var foo = {
a: 3,
b: 'yellow',
c: {
d: 5,
e: 'green'
}
},
bar = {
b: 'yellow',
c: {
d: 5,
e: 'green'
}
};
What is the best way to check that foo
contains bar
?
I am already using Lodash in my application, so you can use functions from that library if it makes it easier. Otherwise, vanilla JS is fine.
[EDIT]
Well, let me try to explain what I mean when I use term 'contain'. I will do it in LoDash terminology.
LoDash has _.extend
method, so that if have 2 objects:
var obj1 = {a:1, b:2},
obj2 = {b:4, c:{d:'green', e:5}}
then the operation _.extend(obj1, obj2)
will 'extend' obj1
- it will now have the value
{a:1, b:4, c:{d:'green', e:5}}
i.e. obj1
'contains' obj2
now.
function containsObject(parent, child) {
return !!_.findWhere(_.flatten([parent]), child);
}
alert(containsObject(foo, bar)); // alerts "true"