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

สร้าง Nested JSON Object จากสตริงคู่ตัวอักษร - JavaScript

จากสตริงที่มีตัวอักษรเป็นคู่ (AA BB CC DD EE) สร้าง Nested Object แบบลูกโซ่

ตัวอย่าง

'AABBCCDDEE'
→ { code: 'AA', sub: { code: 'BB', sub: { code: 'CC', sub: { code: 'DD', sub: { code: 'EE', sub: {} } } } } }

ตัวอย่างโค้ด

const constructObject = str => {
  const res = {};
  let ref = res;
  
  while (str) {
    const pair = str.substring(0, 2);
    str = str.substring(2);
    ref.code = pair;
    ref.sub = {};
    ref = ref.sub;
  }
  return res;
};

console.log(JSON.stringify(constructObject('AABBCCDDEE'), null, 2));

ผลลัพธ์

{
  "code": "AA",
  "sub": {
    "code": "BB",
    "sub": {
      "code": "CC",
      "sub": {
        "code": "DD",
        "sub": {
          "code": "EE",
          "sub": {}
        }
      }
    }
  }
}

การประยุกต์

รูปแบบนี้ใช้ได้กับ: Trie Structure, Decision Tree, Nested Menu, JSON Schema