I'm currently working on reducing a JSON array. Within the array, there are other objects, and my goal is to convert their attributes into their own separate array.
Reduce Function:
// parsed.freight.items is the 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
The reduce function is somewhat functional as it retrieves both the item
values from the items
array. However, I am facing a couple of challenges.
1) The reduce method does not return an array as expected based on the isArray
test.
2) My aim is to create a function that allows me to iterate through all the attributes in the array such as qty
, units
, weight
, paint_eligible
. I'm struggling with passing a variable to the currVal
.
Attempted Solution:
var itemAttribute = 'item';
var resultsReduce = parsed.freight.items.reduce(function(prevVal, currVal){
// Pass parameter here for iteration purposes
// I intend to create a function and loop through the array of attributes
return prevVal += currVal[itemAttribute]
},[])
JSON Data:
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 be reduced
[{
"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"
}
}
Thank you in advance!