[英]How do I merge a JSON child with it's parent using JavaScript
I have a JSON like so:我有一个 JSON 像这样:
{
"parent": {
"type": "Object",
"value": {
"childName": { "type": "String", "value": "A string" }
}
}
}
Pretty much, the pattern is parent
has type
and value
, but I want the value of parent
to be value
差不多,模式是
parent
有type
和value
,但我希望parent
的值是value
{
"parent": {
"childName": "A string"
}
}
How can I set the parent's value to be the child named value
recursively in JavaScript?如何在 JavaScript 中递归地将父值设置为子命名
value
?
The main issue I am having is doing this recursively for a very large file.我遇到的主要问题是对一个非常大的文件递归地执行此操作。
Examples:例子:
The start value of Level
is `{ "type": "string", "value": "A string" } Level
的起始值为`{ "type": "string", "value": "A string" }
I want to make the value of Level
become "A String", making the end value of Level
become "A String"我想让
Level
的值变成“A String”,让Level
的最终值变成“A String”
The start value of parentObject
is { "type": "Object", "value": { "anotherObject": { "type": "string", "value": "Another string" }, "secondObject": { "type": "string", "value": "second string" } } }
parentObject
的起始值为{ "type": "Object", "value": { "anotherObject": { "type": "string", "value": "Another string" }, "secondObject": { "type": "string", "value": "second string" } } }
I want to make the value of parentObject
become { "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" } }
And the value of anotherObject
become "Another string"并且
anotherObject
的值变成“另一个字符串”
Making the final result制作最终结果
{"parentObject": { "anotherObject": "Another string" }, { "secondObject": "second string" }}
The first thing is the object should be symmetric if your want to do it in a recursive way.首先是 object 应该是对称的,如果您想以递归方式进行。
Example:例子:
const input = {
"parentObject": {
"type": "Object",
"value": {
"anotherObject": {
"type": "string",
"value": "Another string"
}
}
}
};
The recursive function is something like this.递归的 function 是这样的。
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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.