我想减少一个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