2

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!

2
  • are you asking how to split your json and inject objects like type and value? or is it something else Commented Sep 23, 2020 at 6:22
  • @rand0m : I want to change json from old structure to new structure ! Commented Sep 23, 2020 at 6:25

3 Answers 3

4

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

Sign up to request clarification or add additional context in comments.

Comments

2

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

2 Comments

Thanks gorak! But I' using nodejs typescipt so it show error Property 'fromEntries' does not exist on type 'ObjectConstructor'.ts(2339)
@JavaDevBeginner Then one of solution with reduce will work. Or if your using lodash or underscore. You have an fromPairs method which will work instead of Object.fromEntries
0

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

1 Comment

Yes. I want to change json from old structure to new structure !

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.