用JS减少JSON

时间:2016-12-16 18:25:46

标签: javascript json parsing reduce

我正在尝试减少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函数有点工作。它从item数组中获取items。但是我遇到了一些问题。

1)reduce不会传回一个数组。请参阅isArray测试

2)我正在尝试创建一个函数,这样我就可以遍历数组中qtyunitsweightpaint_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"
            }
}

提前致谢

1 个答案:

答案 0 :(得分:2)

获取一系列项目可能需要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]);
    }, []);