我有json:
{
"fullName": "abc",
"age": 19,
...
}
我想使用Nodejs将上面json中的元素添加到下面json 中名为Variables的对象中
{
"variables": {
"fullName" : {
"value" : "abc",
"type" : "String"
},
"age": {
"value" : 19,
"type": "Number"
},
...
}
}
请帮我处理这个案子!
您可以将Object.entries
与.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);
我们可以首先对该对象的entries
进行映射,然后使用Object.fromentries
转换该对象。这里有一个实现:
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});
您是否正在寻找从文件中获取结构的JSON.parse,然后从结构中创建JSON的JSON.stringify?