構造 JavaScript 中的巢狀 JSON 物件
我們有一種特殊型別的字串,其中包含成對字元,如下所示:-
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": {} } } } } }
廣告