2017-03-31 6 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

그 중 하나가 문자열이기 때문일 수 있습니다. 번호에 대해서만 연산을 수행 할 수 있습니다. 당신은 내가 'amount amount'단계에서했던 것과 비슷한 것으로 번호로 변환해야하고, 숫자를 추가 한 다음 (필요한 경우) 문자열로 서식을 지정해야합니다. – weirdan