在 JavaScript 中將 JSON 陣列轉換為普通 JSON


假設我們有一個這樣的 JSON 陣列,其中包含鍵/值對物件——

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

我們需要編寫一個 JavaScript 函式,用於接收這樣一個數組。

該函式應該準備一個新陣列,其中將資料簡單地針對鍵值列出,而不是這種複雜的結構。

因此,對於上述陣列,輸出應如下所示——

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' }
}

更新時間: 2020-11-24

637 次瀏覽

開啟你的 職業

透過完成課程獲得認證

開始
廣告