我有以下JSON字符串 -
{
"fruits":[
{
"name":"apples",
"id":"1"
},
{
"name":"bananas",
"id":"2"
},
{
"name":"oranges",
"id":"3"
},
{
"name":"pears",
"id":"4"
},
{
"name":"grapes",
"id":"5"
},
{
"name":"strawberries",
"id":"6"
}
],
"links":[
{
"source":"1",
"target":"2"
},
{
"source":"1",
"target":"3"
},
{
"source":"1",
"target":"5"
},
{
"source":"4",
"target":"5"
},
{
"source":"4",
"target":"6"
}
]
}
我的问题是有没有办法通过算法运行字符串,该算法只显示节点和连接的链接。因此,在示例中,JSON应该是(在删除冗余数据之后) -
{
"fruits":[
{
"name":"apples",
"id":"1"
},
{
"name":"pears",
"id":"4"
},
{
"name":"grapes",
"id":"5"
}
],
"links":[
{
"source":"1",
"target":"5"
},
{
"source":"4",
"target":"5"
}
]
}
葡萄与苹果和梨都有关系。我已经创建了一个算法来删除任何有效的重复项,但是不能破解它以显示链接条目。
我已遍历所有目标值
var lookup = {};
var result = [];
var links = jsonString['links'];
for (var item, i = 0; item = links[i++];) {
var name = item.target;
if (!(name in lookup)) {
lookup[name] = 1;
// remove unique values to leave only multiple occurances
// then based on the source and target values removes none related from fruits and rebuild JSON
}
}