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

แปลง JSON อาร์เรย์เป็น JSON ธรรมดาใน JavaScript


สมมติว่าเรามี JSON อาร์เรย์พร้อมออบเจกต์ key/value pair ดังนี้

const arr = [{ 
  "key": "name", 
  "value": "john" 
}, { 
  "key": "number", 
  "value": "1234" 
}, { 
  "key": "price", 
  "value": [{ 
    "item": [{ 
      "item": [{ 
        "key": "quantity", 
        "value": "20" 
      }, 
      { 
        "key": "price", 
        "value": "200" 
      }] 
    }] 
  }] 
}];

เราต้องเขียนฟังก์ชัน JavaScript ที่รับอาร์เรย์ดังกล่าว

ฟังก์ชันควรเตรียมอาร์เรย์ใหม่ที่ข้อมูลถูกแสดงเพียงแค่ key-value แทนโครงสร้างซับซ้อนนี้

ดังนั้น สำหรับอาร์เรย์ข้างต้น ผลลัพธ์ควรเป็นดังนี้

const output = { 
  "name": "john", 
  "number": "1234", 
  "price": { 
    "quantity": "20", 
    "price": "200" 
  } 
};

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

โค้ดสำหรับการทำงานนี้จะเป็นดังนี้

const arr = [{ 
  "key": "name", 
  "value": "john" 
}, { 
  "key": "number", 
  "value": "1234" 
}, { 
  "key": "price", 
  "value": [{ 
    "item": [{ 
      "item": [{ 
        "key": "quantity", 
        "value": "20" 
      }, 
      { 
        "key": "price", 
        "value": "200" 
      }] 
    }] 
  }] 
}]; 
const simplify = (arr = []) => { 
  const res = {}; 
  const recursiveEmbed = function(el){ 
    if ('item' in el) { 
      el.item.forEach(recursiveEmbed, this); 
      return; 
    }; 
    if (Array.isArray(el.value)) { 
      this[el.key] = {}; 
      el.value.forEach(recursiveEmbed, this[el.key]); 
      return; 
    }; 
    this[el.key] = el.value; 
  }; 
  arr.forEach(recursiveEmbed, res); 
  return res; 
}; 
console.log(simplify(arr));

ผลลัพธ์

ผลลัพธ์ในคอนโซลจะเป็นดังนี้

{
  name: 'john', 
  number: '1234', 
  price: { quantity: '20', price: '200' } 
}