I have json :
{
"fullName": "abc",
"age": 19,
...
}
I want use Nodejs to add element in above json to object named Variables in below json
{
"variables": {
"fullName" : {
"value" : "abc",
"type" : "String"
},
"age": {
"value" : 19,
"type": "Number"
},
...
}
}
Please help me this case!
I have json :
{
"fullName": "abc",
"age": 19,
...
}
I want use Nodejs to add element in above json to object named Variables in below json
{
"variables": {
"fullName" : {
"value" : "abc",
"type" : "String"
},
"age": {
"value" : 19,
"type": "Number"
},
...
}
}
Please help me this case!
Share Improve this question edited Sep 23, 2020 at 6:22 Java Dev Beginner asked Sep 23, 2020 at 6:17 Java Dev BeginnerJava Dev Beginner 3592 gold badges5 silver badges14 bronze badges 2- are you asking how to split your json and inject objects like type and value? or is it something else – rand0m Commented Sep 23, 2020 at 6:22
- @rand0m : I want to change json from old structure to new structure ! – Java Dev Beginner Commented Sep 23, 2020 at 6:25
3 Answers
Reset to default 4You can use Object.entries
with .reduce()
let data = {
"fullName": "abc",
"age": 19,
}
let result = Object.entries(data).reduce((a, [key, value]) => {
a.variables[key] = { value, type: typeof value}
return a;
}, { variables: {}})
console.log(result);
We can first entries
of that object and then map it accordingly after that we convert that object using Object.fromentries
. Here is an implementation:
const obj = { "fullName": "abc", "age": 19 };
const result = Object.fromEntries(Object.entries(obj).map(([k,value])=>[k,{value, type:typeof value}]));
console.log({variable:result});
Are you looking for JSON.parse to get a struct from your file, then JSON.stringify to create a json from your struct ?