我正在尝试减少 JSON 数组。数组里面是其他对象,我正在尝试将属性变成它们自己的数组。
归约函数:
// 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.
variable here
尝试:
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"
}
}
提前致谢
最佳答案
您可能需要 Array#map
用于获取项目数组
var resultsReduce = parsed.freight.items.reduce(function (array, object) {
return array.concat(object.item);
}, []);
与给定键相同,括号表示为 property accessor
object.property object["property"]
var key = 'item',
resultsReduce = parsed.freight.items.reduce(function (array, object) {
return array.concat(object[key]);
}, []);
关于javascript - 用 JS 减少 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41190321/