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

แปลง key แบบ square bracket เป็น nested object - JavaScript

แปลง key string "object[foo][bar][ya]" เป็น nested object

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

const obj = { "object[foo][bar][ya]": 100 };
const constructDotNotation = obj => {
  const keys = Object.keys(obj)[0].split('[').map(el => {
    return el.replace(']', '');
  });
  let res = {};
  keys.reverse().forEach(key => {
    if (Object.keys(res).length === 0) {
      res[key] = obj[Object.keys(obj)[0]];
    } else {
      const temp = {};
      temp[key] = res;
      res = temp;
    }
  });
  return res;
};
console.log(JSON.stringify(constructDotNotation(obj), undefined, 4));

ผลลัพธ์

{
  "object": {
    "foo": {
      "bar": {
        "ya": 100
      }
    }
  }
}

คำอธิบาย: split('[') แยกเป็น ["object", "foo]", "bar]", "ya]"] map(el => el.replace(']', '')) ลบ ] → ["object", "foo", "bar", "ya"] reverse() เรียกจากในออกมา สร้าง nested object ชั้นในก่อน