最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Create json object dynamic in nodejs - Stack Overflow

programmeradmin2浏览0评论

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
Add a ment  | 

3 Answers 3

Reset to default 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);

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 ?

发布评论

评论列表(0)

  1. 暂无评论