在 JavaScript 中构建嵌套 JSON 对象

javascriptweb developmentfront end technologyobject oriented programming更新于 2026/2/3 16:44:17

我们有一种特殊的字符串,其中包含成对的字符,例如这样的 −

const str = "AABBCCDDEE";

我们需要根据此字符串构建一个对象,该对象应如下所示 −

const obj = {
   code: "AA",
   sub: {
      code: "BB",
      sub: {
         code: "CC",
         sub: {
            code: "DD",
            sub: {
               code: "EE",
               sub: {}
            }
         }
      }
   }
};

请注意,对于字符串中的每一对唯一配对,我们都有一个新的子对象,并且任何级别的代码属性都代表特定的配对。

我们可以使用递归方法解决这个问题。

我们将递归迭代字符串以选择特定的配对并为其分配一个新的子对象。

因此,让我们编写该函数的代码 −

示例

其代码为 −

const str = "AABBCCDDEE";
const constructObject = str => {
   const res = {};
   let ref = res;
   while(str){
      const words = str.substring(0, 2);
      str = str.substr(2, str.length);
      ref.code = words;
      ref.sub = {};
      ref = ref.sub;
   };
   return res;
};
console.log(JSON.stringify(constructObject(str), undefined, 4));

输出

控制台中的输出将是 −

{
   "code": "AA",
   "sub": {
      "code": "BB",
      "sub": {
         "code": "CC",
         "sub": {
            "code": "DD",
            "sub": {
               "code": "EE",
               "sub": {}
            }
         }
      }
   }
}

相关文章


有用资源