Reputation: 33
I need to create an object from a JSON file. The Input Json file looks like this.
{
"test":{
"Record":1,
"RecordValues":{
"Address":"3330 Bay Rd.",
"City":"Los Angeles",
"SecondObject":{
"1":"eins",
"2":"zwei"
}
}
}
}
What i have so far is this function..
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;
}
The output object should be as follows.
[
{ "title":"Record : 1" },
{
"title":"RecordValues",
"children":[
{ "title":"Address : 3330 Bay Rd." },
{ "title":"City : Los Angeles" },
{
"title":"SecondObject",
"children":[
{ "title":"1 : eins" },
{ "title":"2 : zwei" }
]
}
]
}
]
Upvotes: 3
Views: 195
Reputation: 37755
You can use Object.entries
and reduce
with recursion
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))
Upvotes: 1
Reputation: 35222
You could use Object.entries()
and recursively call the function if the nested value is an object:
(The Object(value) === value
checks if the value
is an object which is not null
)
const obj = {test:{Record:1,RecordValues:{Address:"3330 Bay Rd.",City:"Los Angeles",SecondObject:{1:"eins",2:"zwei"}}}};
function transform(obj) {
return Object.entries(obj).map(([key, value]) => {
if(Object(value) === value)
return { title: key, children: transform(value) }
else
return { title: `${key} ${value}` }
})
}
console.log(transform(obj.test))
Upvotes: 1
Reputation: 370679
Here's one possible approach, recursively iterating over the Object.entries
:
const input = {
"test": {
"Record": 1,
"RecordValues": {
"Address": "3330 Bay Rd.",
"City": "Los Angeles",
"SecondObject": {
"1": "eins",
"2": "zwei"
}
}
}
};
const makeNested = (currInput) => {
return Object.entries(currInput).map(([key, val]) => (
typeof val !== 'object'
? { title: `${key} : ${val}` }
: {
title: key,
children: makeNested(val)
}
))
};
console.log(makeNested(input.test));
Upvotes: 1