我必须在js中制作一个网络地图,其中的组件(等)中包含一些组件。我使用canvas通过Fabric.js库执行此操作。
我从这样的api获取一个json:
{
"name": "BAY_01",
"type": "Bay",
"_links": [{
"name": "SERVER_01",
"type": "Server",
"_links": [{
"name": "CPU"
}, {
etc...
}],
}]
}
我认为实现这些组件绘制的最佳方法是使其递归,但我不知道该怎么做。
有人可以帮助我解决我的问题吗?
答案 0 :(得分:1)
以下是按名称使用递归的示例。基本上,您需要确定JSON对象的属性是否为数组,然后再次调用递归函数,否则检查属性名称是否为“ name” ,然后调用函数以按名称绘制形状:
exec sp_executesql N'SELECT
[Extent1].[UserID] AS [UserID],
[Extent1].[ProductID] AS [ProductID],
[Extent1].[OrganisationID] AS [OrganisationID],
....
[Extent1].[LastAccessedDate] AS [LastAccessedDate]
FROM [dbo].[UserProduct] AS [Extent1]
WHERE [Extent1].[ProductID] = @EntityKeyValue1',N'@EntityKeyValue1 int',@EntityKeyValue1=79
请记住在递归函数之后使用var obj = {
"name": "BAY_01",
"type": "Bay",
"_links": [{
"name": "SERVER_01",
"type": "Server",
"_links": [{
"name": "CPU"
}, {
"name": "SERVER_02",
"type": "Server",
"_links": [{
"name": "CPU2"
}]
}]
}]
};
function goThroughtObject(obj, name) {
var key;
if (obj instanceof Array) {
return obj.map(function(value) {
if (typeof value === "object") {
goThroughtObject(value, name)
}
return value;
})
} else {
for (key in obj) {
if (obj.hasOwnProperty(key)) {
if (key === name){
drawByName(obj[key]);
}
if (obj[key] instanceof Array || (obj[key] !== null && obj[key].constructor === Object)) {
goThroughtObject(obj[key], name);
}
}
}
}
};
//implement fabricjs logic in this function
function drawByName (name) {
console.log("Fabricjs will draw a: " + name);
}
goThroughtObject(obj, 'name');
函数,只要这样做会更好。