2017-07-24 81 views
-4

我想將JavaScript對象的結構更改爲另一個結構。我的問題是,對於每個對象,我要創建多達三個不同的對象:如何更改對象結構

我輸入:

[ 
    {date: "21-05", cash: "500", card: "200", points: "100"}, 
    {date: "26-05", card: "100", points: "50"} 
] 

所需的輸出:

[ 
    {date: "21-05", amount: "500", paymentType: cash }, 
    {date: "21-05", amount: "200", paymentType: card }, 
    {date: "21-05", amount: "200", paymentType: points }, 
    {date: "26-05", amount: "100", paymentType: card }, 
    {date: "26-05", amount: "50", paymentType: points } 
] 

現金,卡,點是全球const

+3

你嘗試過什麼?循環它並將三個新對象推送到一個數組。 – Prinzhorn

+2

這兩個例子都是無效的JSON。 – Quentin

+0

'date:「21-05」,'不是JSON。在JSON中,密鑰必須包含在雙引號中。您顯示的對象是JavaScript對象。 JavaScript中的JSON是數據的字符串表示形式,因此JSON數據始終是字符串類型。 –

回答

0

你可以遍歷數組和按鍵,並檢查是否不date,然後建立與數據的新對象。收集直到訪問所有對象。

var data = [{ date: "21-05", cash: "500", card: "200", points: "100" }, { date: "26-05", card: "100", points: "50" }], 
 
    result = data.reduce(function (r, o) { 
 
     Object.keys(o).forEach(function (k) { 
 
      if (k !== 'date') { 
 
       r.push({ date: o.date, amount: o[k], paymentType: k }); 
 
      } 
 
     }); 
 
     return r; 
 
    }, []); 
 
    
 
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

0

您可以使用一對for循環:

const data = [ 
 
    {date:"21-05", cash: "500", card:"200", points:"100"}, 
 
    {date: "26-05", card:"100", points:"50"} 
 
]; 
 

 
const result = []; 
 
for (let row of data) { 
 
    for (let key in row) { 
 
     if (key !== 'date') { 
 
      result.push({ 
 
       data: row.date, 
 
       amount: row[key], 
 
       paymentType: key 
 
      }); 
 
     } 
 
    } 
 
} 
 

 
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }