我有一系列深度未知的对象。从深度上讲,我的意思是我不知道每个孩子都有孩子。对不起,我找不到合适的词来进一步解释它。例如:
gl.generateMipmap
是否可以在javascript中编写函数,该函数将以匹配父ID的顺序嵌套对象?
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
//gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
// Upload the image into the texture.
var mipLevel = 0; // the largest mip
var internalFormat = gl.RGBA; // format we want in the texture
var srcFormat = gl.RGBA; // format of data we are supplying
var srcType = gl.UNSIGNED_BYTE; // type of data we are supplying
gl.texImage2D(gl.TEXTURE_2D,
mipLevel,
internalFormat,
srcFormat,
srcType,
image);
gl.generateMipmap(gl.TEXTURE_2D)
嵌套对象以在以后使用它呈现数据而不在每一层询问是否有子级的最佳实践是什么?
答案 0 :(得分:3)
这里是一种创建映射以跟踪每个项目在数组中的位置的方法。然后,遍历该数组并将其添加到适当父级的children
数组中。
const arr = [
{id: 1},
{id: 2, parentId: 1},
{id: 3, parentId: 2},
{id: 4, parentId: 3},
{id: 5, parentId: 2},
{id: 6, parentId: 1},
]
let map = {};
arr.forEach((el, i) => {
map[el.id] = i;
el.children = [];
});
let root = [];
arr.forEach(el => {
if (!el.parentId) {
root.push(el);
} else {
arr[map[el.parentId]].children.push(el);
}
});
console.log(root);
答案 1 :(得分:0)
使用一个对象来保留对孩子的引用。
var data = [{ id: 1 }, { id: 2, parentId: 1 }, { id: 3, parentId: 2 }, { id: 4, parentId: 3 }, { id: 5, parentId: 2 }, { id: 6, parentId: 1 }],
tree = function (data, root) {
var o = {};
data.forEach(function (a) {
if (o[a.id] && o[a.id].children) {
a.children = o[a.id].children;
}
o[a.id] = a;
o[a.parentId] = o[a.parentId] || {};
o[a.parentId].children = o[a.parentId].children || [];
o[a.parentId].children.push(a);
});
return o[root].children;
}(data, undefined);
console.log(tree);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 2 :(得分:0)
var array = [
{id: 1},
{id: 2, parentId: 1},
{id: 3, parentId: 2},
{id: 4, parentId: 3},
{id: 5, parentId: 2},
{id: 6, parentId: 1},
];
const findParent = (list, parentId) => {
list = list || [];
return list.find(el => el.id === parentId);
}
const findDeepParent = (list, parentId) => {
for(const i = 0; i < list.length; i++) {
const element = list[i];
const parent = findParent(list, parentId);
if (parent) {
return parent
} else if(element.children) {
return findDeepParent(element.children, parentId);
};
}
}
const objs = array.reduce((result, obj) => {
let found = false;
if (obj.parentId) {
var parent = findDeepParent(result, obj.parentId)
if (parent) {
parent.children = parent.children || [];
parent.children.push(obj);
found = true;
}
}
if(!found) {
result.push(obj);
}
return result;
}, []);
console.log(objs);
这可以解决您的问题