ภาพรวม
บทความนี้สาธิตวิธีสร้างออบเจกต์จากสตริง โดยใช้ตัวอักษรที่ไม่ซ้ำกันในสตริงเป็น Keys และกำหนด Value เริ่มต้นเป็น 0
ตัวอย่าง
const str = 'hello world!';
// ผลลัพธ์: { h: 0, e: 0, l: 0, o: 0, ' ': 0, w: 0, r: 0, d: 0, '!': 0 }
การนำไปใช้
const stringToObject = (str) => {
return str.split('').reduce((acc, val) => {
acc[val] = 0;
return acc;
}, {});
};
console.log(stringToObject('hello world!'));
console.log(stringToObject('is it an object'));
ผลลัพธ์
{ h: 0, e: 0, l: 0, o: 0, ' ': 0, w: 0, r: 0, d: 0, '!': 0 }
{ i: 0, s: 0, ' ': 0, t: 0, a: 0, n: 0, o: 0, b: 0, j: 0, e: 0, c: 0 }
การประยุกต์ใช้: นับความถี่ตัวอักษร (Character Frequency)
const charFrequency = (str) => {
return str.split('').reduce((acc, val) => {
acc[val] = (acc[val] || 0) + 1;
return acc;
}, {});
};
console.log(charFrequency('hello world!'));
// { h: 1, e: 1, l: 3, o: 2, ' ': 1, w: 1, r: 1, d: 1, '!': 1 }
วิธีการทันสมัย
// ใช้ Object.fromEntries และ Map
const stringToObjectModern = (str) =>
Object.fromEntries([...new Set(str)].map(char => [char, 0]));
// นับความถี่แบบหนึ่งบรรทัด
const charFrequencyModern = (str) =>
[...str].reduce((acc, c) => (acc[c] = (acc[c] || 0) + 1, acc), {});
กรณีการใช้งานจริง
- สร้าง Character Map สำหรับการเข้ารหัส/ถอดรหัส
- วิเคราะห์ความถี่ตัวอักษรใน Cryptanalysis
- สร้าง Vocabulary สำหรับ NLP
- Validation: ตรวจสอบว่าสตริงประกอบด้วยตัวอักษรที่อนุญาตเท่านั้น
ข้อควรระวัง
- Key ใน Object ต้องเป็น String/Symbol เท่านั้น ตัวเลขจะถูกแปลงเป็น String
- ตัวอักษรซ้ำจะถูก overwrite (แต่ Value เดียวกันจึงไม่เป็นปัญหา)
- Unicode Surrogate Pairs: ใช้ `[...str]` แทน `str.split('')`