JSON配列を減らそうとしています。配列の内部には他のオブジェクトがあります。属性を独自の配列に変換しようとしています。JSONをJSで減らす
機能を削減:
// 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
軽減機能が働くの一種です。これはitems
配列からitem
の両方を取得します。しかし、私はいくつかの問題を抱えています。
1)reduceは配列を返しません。私は、関数を作成しようとしています
2)isArray
テストを参照してくださいので、私はでき配列qty
、units
、weight
、paint_eligable
のすべての属性をループ。
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"
}
}
おかげ
としてブラケット表記を使用すると、配列内のアイテムから値のみを取得したいですか?または項目の合計? –
var key = ['item'、 'qty'、 'units'、 'paint_eligible'、 'weight']; var resultsReduce = new Object(); key.forEach(関数(アイテム){ resultsReduce [商品] = parsed.freight.items.reduce(関数(配列オブジェクト){ 戻りarray.concat(オブジェクト[アイテム]); }、[]) ; })これは私が行ったことです。私のメモの投稿だけ – nzaleski