我有一些对象类型数据。
每个对象都有相同的键,children
。
children
可以有另一个children
。
const testColumns = {
label: '테스트 수',
width: 320,
children: [
{
label: '1-1111',
width: 160,
children: [
{
key: 'testCnt',
label: '2-3333',
width: 80,
},
{
key: 'exceptionCnt',
label: '2-4444',
width: 80,
children: [
{
key: 'allTestCnt',
label: '3-5555',
width: 80,
},
{
key: 'allExceptionCnt',
label: '3-6666',
width: 80,
},
]
}
]
}
]
};
我必须将 testColumns
中的其他对象重新排列为 returnColumns
。
像这样。
let returnColumns = [];
testColumns.map((obj)=>{
if(obj.children){
obj.children.map((child, firstChildIndex)=>{
returnColumns['children'] = [];
returnColumns.push({
property: child.key,
header: {
label: child.label,
},
props: {
style: {
width: child.width
}
});
if(child.children){
returnColumns[firstChildIndex]['children'] = [];
child.children.map((secondChild, secondChildIndex)=>{
returnColumns[firstChildIndex]['children'].push({
property: secondChild.key,
header: {
label: secondChild.label,
},
props: {
style: {
width: secondChild.width
}
});
})
}
});
}
})
我尝试将上面的代码变成递归函数。像这样。
function recursiveIteration(object, callback) {
for (let property in object) {
if (object.hasOwnProperty(property)) {
if (typeof object[property] == "object"){
recursiveIteration(object[property]);
// ...
// ...
}
}
}
}
但我不知道它是如何工作的。
以上代码是示例。这并不完美。 Here is jsfiddle link
这是我想要的结果
const test = {
property: undefined,
header : {
label: 'TEST1'
},
props: {
style: {
width: 320,
}
},
children: [
{
property: 'test',
header : {
label: 'test'
},
props: {
style: {
width: 160,
}
},
},
{
property: undefined,
header : {
label: '2-4444'
},
props: {
style: {
width: 160,
}
},
children: [
{
property: 'allTestCnt',
header : {
label: '3-5555'
},
props: {
style: {
width: 80,
}
},
},
{
property: 'allExceptionCnt',
header : {
label: '3-6666'
},
props: {
style: {
width: 80,
}
},
}
]
}
]
};
}
最佳答案
您可以使用递归回调来映射数组的值。
var testColumns = { label: '테스트 수', width: 320, children: [{ label: '1-1111', width: 160, children: [{ key: 'testCnt', label: '2-3333', width: 80, }, { key: 'exceptionCnt', label: '2-4444', width: 80, children: [{ key: 'allTestCnt', label: '3-5555', width: 80, }, { key: 'allExceptionCnt', label: '3-6666', width: 80, }, ] }] }] },
result = [testColumns].map(function iter(o) {
var temp = {
property: undefined,
header: { label: o.label },
props: { style: { width: o.width } }
};
if (o.children) {
temp.children = o.children.map(iter);
}
return temp;
})[0];
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
关于javascript - 如何在javascript中使用递归代码在对象中创建内部对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44195559/