javascript - 从 JSON 递归创建对象
问题描述
我需要从 JSON 文件创建一个对象。输入 Json 文件如下所示。
{
"test":{
"Record":1,
"RecordValues":{
"Address":"3330 Bay Rd.",
"City":"Los Angeles",
"SecondObject":{
"1":"eins",
"2":"zwei"
}
}
}
}
到目前为止我所拥有的是这个功能..
var test = [];
function recFunc(obj, parent_id = null) {
for(var i in obj) {
if(typeof obj[i] == "object" && obj[i] !== null) {
test.push({title: i, children: []});
recFunc(obj[i], (test.length-1));
}else {
if(parent_id != null) {
test[parent_id].children.push({title: (i + " : " + obj[i])});
}else {
test.push({title: (i + " : " + obj[i])});
}
}
}
return test;
}
输出对象应如下所示。
[
{ "title":"Record : 1" },
{
"title":"RecordValues",
"children":[
{ "title":"Address : 3330 Bay Rd." },
{ "title":"City : Los Angeles" },
{
"title":"SecondObject",
"children":[
{ "title":"1 : eins" },
{ "title":"2 : zwei" }
]
}
]
}
]
解决方案
您可以使用Object.entries
andreduce
递归
let obj = {"test":{"Record":1,"RecordValues":{"Address":"3330 Bay Rd.","City":"Los Angeles","SecondObject":{"1":"eins","2":"zwei"}}}}
let recursive = (obj) =>
Object.entries(obj).reduce((op,[key,value]) => {
let final = typeof value === 'object' ? {title:key, children:recursive(value)}
: {title: `${key}: ${value}`}
return op.concat(final)
},[])
console.log(recursive(obj.test))
推荐阅读
- php - Symfony - 在 null 上调用成员函数 setFunction()
- scala - Scala - 类型推断不适用于数组作为函数 args
- algorithm - 加权作业调度 - 它是如何工作的
- python - 在 python 中使用 pandas 计算滚动季度(替代方案?)
- javascript - DataTable 不是函数的错误
- php - Simplenews 通讯网址?
- java - 在不同时区之间格式化时间的正确方法是什么?
- python - 四舍五入到任何给定值python
- mysql - 如何根据 A 列中的数据将 B 列的 SQL 搜索结果汇总为总和?
- scala - 高阶函数