文字列を階層オブジェクトに変換する-JavaScript
たとえば、次のように、カップルで文字を含む特別な種類の文字列があるとします-
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": {}
}
}
}
}
} -
JavaScript文字列をブール値に変換します
JavaScriptで文字列をブール値に変換するためのコードは次のとおりです- 例 <!DOCTYPE html> <html> <head> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } </style> </head> <body> <h1>Converting strin
-
文字列をJavaScriptオブジェクトに変換する方法は?
以下は、文字列をJavaScriptオブジェクトに変換するコードです- 例 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> &nbs