[英]How to check if an object is a “sub-object” in Javascript?
我被困在FreeCodeCamp的算法上。 基本上,如果我有一個object1{a:1,b:2,c:3}
並有另一個object2{a:1,b:2}
。 如何檢查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));
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
遍歷對象B的屬性,並檢查每個屬性是否包含在對象A中並具有相同的值。
偽代碼:
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
請參閱如何枚舉JavaScript對象的屬性? 作為開始。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.