Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

แปลงสตริงเป็นอ็อบเจกต์แบบลำดับชั้น - JavaScript

สมมติว่าเรามีสตริงพิเศษที่ประกอบด้วยตัวอักษรเป็นคู่ๆ เช่น:

const str = "AABBCCDDEE";

เราต้องสร้างอ็อบเจกต์จากสตริงนี้ที่มีโครงสร้างดังนี้:

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

สังเกตว่าแต่ละคู่ที่ไม่ซ้ำกันในสตริงจะมี sub-object ใหม่ และ property code ในแต่ละระดับจะแทนคู่นั้นๆ

เราสามารถแก้ปัญหานี้ได้โดยใช้วิธีการ recursive โดยวนซ้ำผ่านสตริงเพื่อเลือกคู่เฉพาะและกำหนด sub-object ใหม่ให้

ตัวอย่าง

โค้ดต่อไปนี้เป็นตัวอย่าง:

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