javascript - 用 JS 减少 JSON

标签 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 函数有点工作。它从 items 数组中获取 item。但是我有几个问题。

1) reduce 没有传回一个数组。参见 isArray 测试

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

相关文章:

javascript - 菜单使用 Bootstrap 将图像向下推到移动版本中?

javascript - 选择字段和自定义输入仅显示输入值作为结果 sweetalert2

java - 使用 Jackson 数据绑定(bind)跳过嵌套字段?

python - 区分pyparsing中的匹配项

javascript - 将 Rails 路线映射到 Ember 路线

javascript - 如何在 Javascript 中使用提示在对象内添加属性?

javascript - 将文本区域值转换为有效的 JSON 字符串

Java 序列化 vs JSON vs XML

Xcode 6.3 解析 SDK 1.7.1 PFTableViewCell 错误 "has incompatible type"

java - 类google搜索引擎爬取解析结果