2016-12-16 25 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