简体   繁体   English

如何检查对象是否是Javascript中的“子对象”?

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

I am stuck on the algorithm at FreeCodeCamp. 我被困在FreeCodeCamp的算法上。 Basically, if I have an object1{a:1,b:2,c:3} and have another object2{a:1,b:2} . 基本上,如果我有一个object1{a:1,b:2,c:3}并有另一个object2{a:1,b:2} How do I check if the object2 is a sub-object of the object1? 如何检查object2是否是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 使用Array.prototype.every函数

 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. 遍历对象B的属性,并检查每个属性是否包含在对象A中并具有相同的值。

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? 请参阅如何枚举JavaScript对象的属性? for as a start. 作为开始。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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