0

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?

tata
  • 11
  • 1
  • 5

3 Answers3

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