我想減少一個JSON數組。在數組內部是其他對象,我試圖將屬性變成他們自己的數組。用JS減少JSON
Reduce函數:
// parsed.freight.items is path
var resultsReduce = parsed.freight.items.reduce(function(prevVal, currVal){
return prevVal += currVal.item
},[])
console.log(resultsReduce);
// two items from the array
// 7205 00000
console.log(Array.isArray(resultsReduce));
// false
reduce函數是種工作。它從items
陣列獲得item
。不過,我遇到了一些問題。 1)Reduce不傳回數組。見isArray
測試
2)我試圖做一個功能,所以我可以通過所有的數組qty
,units
,weight
,paint_eligable
在屬性的循環。我不是一個變量傳遞給這裏
的currVal.
變量嘗試:
var itemAttribute = 'item';
var resultsReduce = parsed.freight.items.reduce(function(prevVal, currVal){
// pass param here so I can loop through
// what I actually want to do it create a function and
// loop through array of attributes
return prevVal += currVal.itemAttribute
},[])
JSON:
var request = {
"operation":"rate_request",
"assembled":true,
"terms":true,
"subtotal":15000.00,
"shipping_total":300.00,
"taxtotal":20.00,
"allocated_credit":20,
"accessorials":
{
"lift_gate_required":true,
"residential_delivery":true,
"custbodylimited_access":false
},
"freight":
{
"items":
// array to reduce
[{
"item":"7205",
"qty":10,
"units":10,
"weight":"19.0000",
"paint_eligible":false
},
{ "item":"1111",
"qty":10,
"units":10,
"weight":"19.0000",
"paint_eligible":false
}],
"total_items_count":10,
"total_weight":190.0},
"from_data":
{
"city":"Raleigh",
"country":"US",
"zip":"27604"},
"to_data":
{
"city":"Chicago",
"country":"US",
"zip":"60605"
}
}
在此先感謝
你想獲得一個數組只能從項目的價值?或項目的總和? –
var key = ['item','qty','units','paint_eligible','weight']; var resultsReduce = new Object(); (函數(item)){ },[]);}} ; })這是我最終去的。只是張貼我的筆記 – nzaleski