所以在过去的几个小时里,我似乎一直在为此挠头……现在大约 6 个小时,我似乎无法弄清楚。我查看了关于 SO 的各种问题/答案,但没有一个给我答案。
让我首先解释一下这段代码应该做什么。只要它匹配所有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 原型的 find 函数。
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.
一切似乎都在工作,直到它再次出现,然后不知何故,对象比较变得一团糟,不再匹配。