Loading...

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

假设我们有一种特殊的字符串,其中包含成对的字符,像这样-

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