javascript - 使用递归函数进行对象转换
问题描述
我有一个看起来像这样的对象:
{
parent: {
child1: {
key: 'value'
},
child2: {
key: 'value'
},
child3: {
key: 'value'
}
}
}
我需要将其转换为如下所示的对象:
{
title: 'parent',
children: [{
title: 'child1',
children: [{
title: 'key',
value: 'value'
}]
}, {
title: 'child2',
children: [{
title: 'key',
value: 'value'
}]
}, {
title: 'child3',
children: [{
title: 'key',
value: 'value'
}]
}]
}
我最终得到了以下功能:
function transform(obj) {
const result = {
title: '',
children: []
};
for (let key in obj) {
let child = obj[key];
result.title = key;
if (typeof(child) === 'string') {
delete result.children;
result.value = child;
} else {
result.children.push(transform(child));
}
}
return result;
}
但是当我运行它时,它会返回以下输出,这是错误的:
{
title: 'parent',
children: [{
title: 'child3',
children: [
{ title: 'key', value: 'value' },
{ title: 'key', value: 'value' },
{ title: 'key', value: 'value' }
]
}]
}
谁能指出我在函数中的错误到底是什么?
解决方案
我认为您为树递归选择了错误的基本情况。将叶子检测放在函数的顶部,而不是在循环中:
function transform(title, value) {
if (typeof value === 'string') {
return {title, value};
} else {
const children = [];
for (let key in obj) {
children.push(transform(key, obj[key]));
}
return {title, children};
}
}
由于您只想要根节点的单个子节点,因此您可以将其称为
console.log(transform('parent', data.parent));
或者
console.log(transform('', data).children[0]);
推荐阅读
- javascript - 通过特殊字符从字符串中查找并提取序列
- angular - 本机脚本 DatePicker 显示错误的月份值
- angular - 在 html 中使用异步管道 => ¿BehaviorSubject 或 Observable?
- time - 标签到轴 - 将 int(秒)转换为小时
- entity-framework - 尝试实体框架代码优先;用法与 Database-first 有什么不同吗?
- python-3.x - 僵尸袭击村庄,蟒蛇
- javascript - R plotly:如何通过带有多个图的图例单击来观察跟踪是隐藏还是显示
- laravel - Connection.php#602 中的 Elasticsearch Missing404Exception
- intellij-idea - 将 Java Web 项目 IBM RAD 迁移到 Intellij
- linux - 什么时候 /proc/
被删除?