2017-03-31 32 views
0

我試圖轉換以下數據集縮小/總:地圖使用Underscorejs

var data = { 
"csrf": "token", 

"items": [ 
{"category": "product1", "image": "image1.jpg", "cost": "$6", "item_totals": [ 
    {"category": "discount", "amount": "-$1.0"}] 
}, 
{"category": "product2", "image": "image2.jpg", "cost": "$8", "item_totals": [ 
    {"category": "discount", "amount": "-$1.2"}] 
}], 

"totals": [ 
{"category": "shipping", "amount": "$0.00", "name": "Shipping", "is_zero": true}, 
{"category": "taxes", "amount": "$0.00", "name": "Taxes", "is_zero": true} 
], 
"total": "$1234", "subtotal": "$1234", "id": abc123, "currency_code": "USD"} 

成一個單一的值,它是所有「量」的值的item_totals陣列(一個或多個)中的總和。我似乎無法做到這一點,同時爲'item_total'數組中的'items'&記錄了不同數量的記錄。任何幫助將是偉大的!

回答

0

var data = { 
 
    "csrf": "token", 
 

 
    "items": [{ 
 
     "category": "product1", 
 
     "image": "image1.jpg", 
 
     "cost": "$6", 
 
     "item_totals": [{ 
 
     "category": "discount", 
 
     "amount": "-$1.0" 
 
     }] 
 
    }, 
 
    { 
 
     "category": "product2", 
 
     "image": "image2.jpg", 
 
     "cost": "$8", 
 
     "item_totals": [ // multiple item_totals 
 
     { 
 
      "category": "discount", 
 
      "amount": "-$1.2" 
 
     }, 
 
     { 
 
      "category": "discount", 
 
      "amount": "-$1.2" 
 
     } 
 
     ] 
 
    }, 
 
    { 
 
     "category": "product2", 
 
     "image": "image2.jpg", 
 
     "cost": "$8", 
 
     "item_totals": [] // empty item_totals 
 
    }, 
 
    { 
 
     "category": "product2", 
 
     "image": "image2.jpg", 
 
     "cost": "$8" 
 
     // absent item_totals 
 
    } 
 

 
    ], 
 

 
    "totals": [{ 
 
     "category": "shipping", 
 
     "amount": "$0.00", 
 
     "name": "Shipping", 
 
     "is_zero": true 
 
    }, 
 
    { 
 
     "category": "taxes", 
 
     "amount": "$0.00", 
 
     "name": "Taxes", 
 
     "is_zero": true 
 
    } 
 
    ], 
 
    "total": "$1234", 
 
    "subtotal": "$1234", 
 
    "id": "abc123", 
 
    "currency_code": "USD" 
 
} 
 

 

 
var totalAmount = _.chain(data.items) 
 
    .map(item => item.item_totals || []) // emit totals 
 
    .tap(console.log) 
 
    .reduce((memo, bucket) => memo.concat(bucket), []) // collect (flatten) 
 
    .tap(console.log) 
 
    .map(total => parseFloat(total.amount.replace('$', ''), 10)) // emit amounts 
 
    .tap(console.log) 
 
    .reduce((ret, amount) => ret + amount, 0) // collect (sum) 
 
    .value(); 
 
console.log(totalAmount);
<script src="http://underscorejs.org/underscore.js"></script>

+0

真棒!太激動了,謝謝。 – Tincdawg

+0

任何想法爲什麼,當我嘗試將此值添加到「總計」數組中發佈的折扣值時,它將連接?注意,我添加了.toFixed(2)進行格式化。謝謝! – Tincdawg

+0

可能是因爲這些是字符串。你只能對數字進行算術運算。您需要將其轉換爲類似於我在「發射量」步驟中所做的操作的數字,然後添加數字,然後將其格式化爲字符串(如有必要)。 – weirdan