2016-12-16 79 views
1

我想减少一个JSON数组。在数组内部是其他对象,我试图将属性变成他们自己的数组。用JS减少JSON

Reduce函数:

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

在此先感谢

+0

你想获得一个数组只能从项目的价值?或项目的总和? –

+0

var key = ['item','qty','units','paint_eligible','weight']; var resultsReduce = new Object(); (函数(item)){ },[]);}} ; })这是我最终去的。只是张贴我的笔记 – nzaleski

回答

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]); 
    }, []); 
+0

谢谢,这确实解决了我的第一个问题。我正在使用'prev,curr.item'或'prev + curr.item',但是这给了我相同的结果。但是有道理。谢谢! – nzaleski

+0

我还是不知道,你想要什么 - 一个数组还是一个数字? –

+1

对不起,我想要一个数组,你给出的第一个答案是正确的。它给了我'['7205','00000']'。这正是我想要的 – nzaleski