สมมติว่าเรามีวัตถุเช่นนี้ −
const obj = { "firstName": "John", "lastName": "Green", "car.make": "Honda", "car.model": "Civic", "car.revisions.0.miles": 10150, "car.revisions.0.code": "REV01", "car.revisions.0.changes": "", "car.revisions.1.miles": 20021, "car.revisions.1.code": "REV02", "car.revisions.1.changes.0.type": "asthetic", "car.revisions.1.changes.0.desc": "Left tire cap", "car.revisions.1.changes.1.type": "mechanic", "car.revisions.1.changes.1.desc": "Engine pressure regulator", "visits.0.date": "2015-01-01", "visits.0.dealer": "DEAL-001", "visits.1.date": "2015-03-01", "visits.1.dealer": "DEAL-002" };
เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่รับออบเจ็กต์ดังกล่าวหนึ่งออบเจ็กต์และคลี่คลายลงในออบเจ็กต์และอาร์เรย์ที่ซ้อนกัน
ดังนั้น ผลลัพธ์สำหรับอาร์เรย์ด้านบนควรมีลักษณะดังนี้ −
const output = { firstName: 'John', lastName: 'Green', car: { make: 'Honda', model: 'Civic', revisions: [ { miles: 10150, code: 'REV01', changes: ''}, { miles: 20021, code: 'REV02', changes: [ { type: 'asthetic', desc: 'Left tire cap' }, { type: 'mechanic', desc: 'Engine pressure regulator' } ] } ] }, visits: [ { date: '2015-01-01', dealer: 'DEAL-001' }, { date: '2015-03-01', dealer: 'DEAL-002' } ] };
ตัวอย่าง
const obj = { "firstName": "John", "lastName": "Green", "car.make": "Honda", "car.model": "Civic", "car.revisions.0.miles": 10150, "car.revisions.0.code": "REV01", "car.revisions.0.changes": "", "car.revisions.1.miles": 20021, "car.revisions.1.code": "REV02", "car.revisions.1.changes.0.type": "asthetic", "car.revisions.1.changes.0.desc": "Left tire cap", "car.revisions.1.changes.1.type": "mechanic", "car.revisions.1.changes.1.desc": "Engine pressure regulator", "visits.0.date": "2015-01-01", "visits.0.dealer": "DEAL-001", "visits.1.date": "2015-03-01", "visits.1.dealer": "DEAL-002" }; const unflatten = (obj = {}) => { const result = {}; let temp, substrings, property, i; for (property in obj) { substrings = property.split('.'); temp = result; for (i = 0; i < substrings.length - 1; i++) { if (!(substrings[i] in temp)) { if (isFinite(substrings[i + 1])) { temp[substrings[i]] = []; } else { temp[substrings[i]] = {}; } } temp = temp[substrings[i]]; } temp[substrings[substrings.length - 1]] = obj[property]; } return result; }; console.log(JSON.stringify(unflatten(obj), undefined, 4));
ผลลัพธ์
และผลลัพธ์ในคอนโซลจะเป็น −
{ "firstName": "John", "lastName": "Green", "car": { "make": "Honda", "model": "Civic", "revisions": [ { "miles": 10150, "code": "REV01", "changes": "" }, { "miles": 20021, "code": "REV02", "changes": [ { "type": "asthetic", "desc": "Left tire cap" }, { "type": "mechanic", "desc": "Engine pressure regulator" } ] } ] }, "visits": [ { "date": "2015-01-01", "dealer": "DEAL-001" }, { "date": "2015-03-01", "dealer": "DEAL-002" } ] }