Java Dev Beginner
Java Dev Beginner

Reputation: 359

Create json object dynamic in nodejs

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!

Upvotes: 2

Views: 4534

Answers (3)

Rajneesh
Rajneesh

Reputation: 5308

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});

Upvotes: 2

Ilijanovic
Ilijanovic

Reputation: 14904

You 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);

Upvotes: 4

Nitsuj
Nitsuj

Reputation: 11

Are you looking for JSON.parse to get a struct from your file, then JSON.stringify to create a json from your struct ?

Upvotes: 0

Related Questions