我有类模式的模型。我需要检查一个类名是否是类的实例。我这样做的原因是因为我在网络工作者中处理数据,从那里我只能获得字符串化数据,因此我无法使用instance of
。
var schema = {
product: {
buildingElements: {
pile: null, // last class
stair: null
},
ventilation: {
duct: null,
airDevice: null
}
}
}
var isClassInstanceOf = function(name, parent, schema){
...
}
var a = isClassInstanceOf('duct', 'ventilation', schema); //true
var b = isClassInstanceOf('airDevice', 'buildingElements', schema); // false
var c = isClassInstanceOf('ventilation', 'product', schema); // true
var e = isClassInstanceOf('duct', 'product', schema); // true
https://jsbin.com/qemunakare/edit?js,output
我真的不知道从哪里开始。不知怎的,我需要用某种while-loop
来走树。
答案 0 :(得分:3)
使用对象,您可以检查父对象。
var schema = { product: { buildingElements: { pile: null, stair: null }, ventilation: { duct: null, airDevice: null } } },
isParentOf = function (name, parent, schema) {
function search(o, p) {
return Object.keys(o).some(function (k) {
if (k === name) {
path = p.concat(k);
return true;
}
return o[k] && typeof o[k] === 'object' && search(o[k], p.concat(k));
});
}
var path = [];
search(schema, []);
return path.indexOf(parent) !== -1;
};
console.log(isParentOf('duct', 'ventilation', schema)); // true
console.log(isParentOf('airDevice', 'buildingElements', schema)); // false
console.log(isParentOf('ventilation', 'product', schema)); // true
console.log(isParentOf('duct', 'duct', schema)); // true
console.log(isParentOf('duct', 'product', schema)); // true

.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:-1)
由于您将数据对象作为字符串,所以您需要做的只是JSON.parse()
这些数据,然后您可以使用instance of
或{{1 }。
示例:
if in
//现在你有一个普通的javascript对象......
然后:
检查属性......
var newSchema = JSON.parse(schema);
等...
Fyi:你应该解析以JSON
提供的对象希望这有帮助。