首页 > 解决方案 > 如何使用 JavaScript 将 JSON 子项与其父项合并

问题描述

我有一个像这样的JSON:

{
  "parent": {
    "type": "Object",
    "value": {
        "childName": { "type": "String", "value": "A string" }
       }
   }
}         

差不多,模式是parenthas typeand value,但我希望的值parentvalue

{
  "parent": {
    "childName": "A string"
  }
}

如何将父级的值设置为valueJavaScript 中递归命名的子级?

我遇到的主要问题是对一个非常大的文件递归地执行此操作。

例子:

的起始值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" }}

这是一个示例 JSON 文件

标签: javascriptjson

解决方案


首先,如果您想以递归方式进行操作,对象应该是对称的。

例子:

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


推荐阅读