nzaleski
nzaleski

Reputation: 441

Reduce JSON with JS

I am trying to reduce a JSON array. Inside the array are other object, I am trying to turn the attributes into their own array.

Reduce Function:

    // 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

The reduce function is kind of working. It gets both item from the items array. However I am having a couple problems.

1) The reduce is not passing back an array. See isArray test

2) I am trying to make a function so I can loop through all of the attributes in the array the qty, units, weight, paint_eligable. I cannot pass a variable to the currVal.variable here

Attempting:

    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"
            }
}

Thanks in advance

Upvotes: 1

Views: 3757

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386654

You may need Array#map for getting an array of items

var resultsReduce = parsed.freight.items.reduce(function (array, object) {
    return array.concat(object.item);
}, []);

The same with a given key, with bracket notation as property accessor

object.property
object["property"]
var key = 'item',
    resultsReduce = parsed.freight.items.reduce(function (array, object) {
       return array.concat(object[key]);
    }, []);

Upvotes: 2

Related Questions