我有一个对象,该对象由具有数组的id的数组组成。例如,arr0应该在arr2 [arr0,arr2]
的一个组中{
arr0:[0,2]
arr1:[1,4]
arr2:[0,2,4]
arr3:[3]
arr4:[1,2,4]
}
我应该有分组对象或数组..任何人都可以帮助逻辑吗?
"0" = {
arr0:[0,2]
arr1:[1,4]
arr2:[0,2,4]
arr4:[1,2,4]
}
"1" ={
arr3:[3]
}
答案 0 :(得分:0)
您可以尝试这样的事情:
var data = { arr0: [0, 2], arr1: [1, 4], arr2: [0, 2, 4], arr3: [3], arr4: [1, 2, 4], }
var r = {};
var prefix = "arr"
var visitedNodes = [];
for (var k in data) {
// This will hold the group
var obj = {};
// This is the index value of first parent in recursion
var v = +k.replace(prefix, '');
// Check if a node is visited using some other node
if (visitedNodes.indexOf(v) === -1)
getChild(k, v, obj);
// If object is updated in loop, update in final object
if (Object.keys(obj).length > 0)
r[v] = obj;
}
console.log(r)
function getChild(key, pos, result) {
data[key].forEach(function(k, i) {
var o = prefix + k;
// Check if current index is same as first parent. If yes, just push and stop loop.
// This will prevent infinite recursion
if (pos === k && !result[o]) {
result[o] = data[o];
visitedNodes.push(k);
return
}
// Check if in current tree chain, current node is not visited
if (!result[o]) {
visitedNodes.push(k)
result[o] = data[o];
getChild((o), pos, result)
}
})
}