javascript - 如何使用 JavaScript 将 JSON 子项与其父项合并
问题描述
我有一个像这样的JSON:
{
"parent": {
"type": "Object",
"value": {
"childName": { "type": "String", "value": "A string" }
}
}
}
差不多,模式是parent
has type
and value
,但我希望的值parent
是value
{
"parent": {
"childName": "A string"
}
}
如何将父级的值设置为value
JavaScript 中递归命名的子级?
我遇到的主要问题是对一个非常大的文件递归地执行此操作。
例子:
的起始值Level
为 `{ "type": "string", "value": "A string" }
我想让值Level
变成“A String”,让最终值Level
变成“A String”
的起始值parentObject
为{ "type": "Object", "value": { "anotherObject": { "type": "string", "value": "Another string" }, "secondObject": { "type": "string", "value": "second string" } } }
我想让成为的parentObject
价值{ "anotherObject": { "type": "string", "value": "Another string" }, "secondObject": { "type": "string", "value": "second string" } }
并且anotherObject
成为“另一个字符串”的值
制作最终结果
{"parentObject": { "anotherObject": "Another string" }, { "secondObject": "second string" }}
解决方案
首先,如果您想以递归方式进行操作,对象应该是对称的。
例子:
const input = {
"parentObject": {
"type": "Object",
"value": {
"anotherObject": {
"type": "string",
"value": "Another string"
}
}
}
};
递归函数是这样的。
const input = {
"parentObject": {
"type": "Object",
"value": {
"anotherObject1": {
"type": "string",
"value": "Another string"
},
"anotherObject2": {
"type": "string",
"value": "Another string"
}
}
}
};
const recursivefn = (obj) => {
const keys = Object.keys(obj);
let acc = {}
keys.forEach((key)=>{
if (typeof obj[key].value === 'object') {
acc = { ...acc, [key]: recursivefn(obj[key].value) };
} else {
acc = { ...acc, [key]: obj[key].value};
}
});
return acc;
}
console.log(recursivefn(input));
推荐阅读
- r - 用 R 中另一列的值替换来自一列的多个观察值
- kotlin - Kotlin - 打印函数表达式
- python - 通过 http 请求将 Matplotlib 图作为 numpy 数组发送
- swift - 被电话打断后继续录制音频,AVAudioRecorder
- c - 是否有一种方式可以逐位修改向量/数组的元素?
- c++ - C++ std::variant vs std::any
- django - Django - 传递一个字典来形成构造函数并在类中全局可用
- sql - JPA SELECT 示例中的单个字符
- php - PHP unlink() 内容仍然出现
- r - BlueSky Statistics - 更改数值统计分析语法以删除 n 和 NA