I am stuck on the algorithm at FreeCodeCamp.
Basically, if I have an object1{a:1,b:2,c:3}
and have another object2{a:1,b:2}
.
How do I check if the object2 is a sub-object of the object1?
Asked
Active
Viewed 1,200 times
0

tata
- 11
- 1
- 5
-
`Object1.hasOwnProperty(Object2)` ? – Rajaprabhu Aravindasamy Mar 28 '16 at 18:47
-
Unfortunately it doesn't seem to work for me – tata Mar 28 '16 at 18:55
-
Do you need to check for presence of the exact ob2 in ob1 or if all the elements of ob2 are present in ob1? – aliasav Mar 28 '16 at 18:56
3 Answers
1
var object1 = {a:1,b:2,c:3};
var object2 = {a:1,b:2};
function isSubObject(object1, object2) {
for (var key in object2) {
// stop if the key exists in the subobject but not in the main object
if (object2.hasOwnProperty(key) && !object1.hasOwnProperty(key)) {
return false;
}
}
return true;
}
document.write('is subobject? ' + isSubObject(object1, object2));

Patrick Lewis
- 83
- 6
0
Using Array.prototype.every
function
var o1 = { a: 1, b: 2, c: 3 }
var o2 = { a: 1, b: 2 }
var r = Object.keys(o2).every(e => o1[e] == o2[e])
document.write(r); // sub-object

isvforall
- 8,768
- 6
- 35
- 50
0
Iterate over the properties of object B and check whether each of them is contained in object A and has the same value.
Pseudo code:
isSubset(A, B):
for each property name as pName of B:
if A contains property with name pName:
if B[pName] equals A[pName]:
continue
return false
return true
See How do I enumerate the properties of a JavaScript object? for as a start.

Community
- 1
- 1

Felix Kling
- 795,719
- 175
- 1,089
- 1,143