用 JS 减少 JSON

Reduce JSON with JS

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

提前致谢

您可能需要 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]);
    }, []);