简体   繁体   中英

How to check if an object is a “sub-object” in Javascript?

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?

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

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 

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM