将字符串转换为分层对象 - JavaScript

javascriptweb developmentfront end technologyobject oriented programming更新于 2025/12/19 18:20:17

假设我们有一种特殊的字符串,其中包含成对的字符,如下所示 −

const str = "AABBCCDDEE";

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

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

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

我们可以使用递归方法解决这个问题。我们将递归迭代字符串以选择特定的对并为其分配一个新的子对象

示例

以下是代码 −

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": {}
               }
           }
       }
   }
}

相关文章


有用资源