1
所以看起來我在過去的幾個小時裏一直在撓撓我的腦袋......大概在6個小時左右,我似乎無法弄清楚。我已經看過各種問題/答案,但他們都沒有給我答案。JavaScript對象比較遞歸中斷
讓我從解釋這段代碼是SUPPOSE做什麼開始。 只要匹配所有object_layout,此代碼將匹配對象屬性與另一個對象。
注意:即使未提供完整的object_layout,我也希望對象匹配。
該數據對象:
var data = {
"some object" : {
name: "some object",
has: "properties",
types: [
"some",
"type",
"of",
"array"
]
},
"another": {
property: false,
name: "another",
object: "here",
test: "this",
object: "strings"
},
"minimal object": {
test: "this too"
},
"minimal matching object": {
property: true,
name: "minimal matching object",
test: "this",
object: "strings"
},
"matching object": {
test: "this",
property: true,
name: "matching object",
this_object: {
some: "object"
}
}
};
甲typeof運算原型函數,可以檢測陣列。稍後會用到。
Object.prototype.typeof = function(object) {
if (!object) { return 'undefined' }
if (typeof(object) === "object" && 'splice' in object && 'join' in object) {
return 'array';
}
return typeof(object);
}
查找功能是對象的原型。
Object.prototype.find = function(object_layout) {
var found_objects;
for (object in this) { // loop through objects in this object.
if (object != 'typeof' && object != 'find') { // skip these functions in our object.
console.log('object: ' + object);
for (property in object_layout) {
if (object_layout.hasOwnProperty(property)) {
var object_type = Object.typeof(object_layout[property]);
if (object_type == 'string') {
console.log('Property ' + property);
console.log('value: ' + object_layout[property]);
if (object_layout[property] != this[object][property]) { // if object_layout property doesnt exist in object.
if (found_objects && found_objects[object]) { console.log(object + " removed from found_objects"); delete found_objects[object]; }// if in found_objects then remove.
console.log("property doesn't exist.");
break; // break to next object.
}
if (!found_objects) { found_objects = {} }
if (!found_objects[object]) { console.log("Added object: " + object); found_objects[object] = this[object]; }
} else if (object_type == 'object') { // recurse into object
console.log('object type: ' + property);
console.log("Recurse: " + JSON.stringify(this[object][property]));
if (this[object][property]) {
this[object][property].find(object_layout[property]); // recurse broken...
}
break; // break to next object
}
}
}
}
}
if (found_objects) { return found_objects; }
return false;
}
函數調用:
var results = data.find(
{
test: "this",
property: true,
this_object: {
some: "object"
}
};
console.log(results), true, 3));
輸出日誌(修剪掉最後一位)
Added object: matching object
Property property
value: true
object type: this_object
Recurse: {"some":"object"}
object: some
Property some
value: object
property doesn't exist.
一切似乎一直在工作,直到它遞歸時,然後以某種方式對象比較得到所有搞砸了,它不再匹配。