2016-05-23 5 views
1

私はオブジェクトの配列を持って、私は他のオブジェクトに変換したい。javascriptでこれを行う最適な方法は何ですか?

var input = [ 
    { "type": "Pant", "brand": "A", "subBrand":"P", "size": "10"}, 
    {"type": "Pant", "brand": "A", "subBrand":"P", "size": "12"}, 
    {"type": "Pant", "brand": "A", "subBrand":"Q", "size": "12"}, 
    {"type": "Pant", "brand": "B", "subBrand":"P", "size": "10"}, 
    {"type": "Shirt", "brand": "A", "subBrand":"P", "size": "10"} 
]; 

出力は、この形式である必要があります。

output = { 
    "Pant" : { 
     "A" : { 
      "P" : { 
      "size" : [10,12] 
      }, 
      "Q" : { 
      "size" : [12] 
      } 
     } 
     "B" : { 
      "P" : { 
      "size" : [10] 
      } 
     } 
    }, 
    "Shirt" : { 
     "A" : { 
      "P" : { 
      "size" : [10] 
      } 
     } 
    } 
}; 

私はコードを書くことを試み、そのは、それぞれの時間は、その以前か来るかどうか、各事を確認するために非常に複雑になってきて。 お知らせください。

答えて

3

Array#forEachを使用して、必要なオブジェクトをデフォルトの空のオブジェクトで構築できます。

var input = [{ "type": "Pant", "brand": "A", "subBrand": "P", "size": "10" }, { "type": "Pant", "brand": "A", "subBrand": "P", "size": "12" }, { "type": "Pant", "brand": "A", "subBrand": "Q", "size": "12" }, { "type": "Pant", "brand": "B", "subBrand": "P", "size": "10" }, { "type": "Shirt", "brand": "A", "subBrand": "P", "size": "10" }], 
 
    output = {}; 
 

 
input.forEach(function (a) { 
 
    output[a.type] = output[a.type] || {}; 
 
    output[a.type][a.brand] = output[a.type][a.brand] || {}; 
 
    output[a.type][a.brand][a.subBrand] = output[a.type][a.brand][a.subBrand] || { size: [] }; 
 
    output[a.type][a.brand][a.subBrand].size.push(a.size); 
 
}); 
 

 
console.log(output);

あなたは少し整頓(およびES6で)それを好きなら、あなたは軽減し、オブジェクトを構築すると、オブジェクトのためのキーを反復処理することができます。

var input = [{ "type": "Pant", "brand": "A", "subBrand": "P", "size": "10" }, { "type": "Pant", "brand": "A", "subBrand": "P", "size": "12" }, { "type": "Pant", "brand": "A", "subBrand": "Q", "size": "12" }, { "type": "Pant", "brand": "B", "subBrand": "P", "size": "10" }, { "type": "Shirt", "brand": "A", "subBrand": "P", "size": "10" }], 
 
    output = {}; 
 

 
input.forEach(function (a) { 
 
    var o = ['type', 'brand', 'subBrand'].reduce((r, k) => r[a[k]] = r[a[k]] || {}, output); 
 
    o.size = o.size || []; 
 
    o.size.push(a.size); 
 
}); 
 

 
console.log(output);

+1

おかげでたくさん使う減らすことができます! – ajayv

+0

@ajayv、こちらをご覧ください:http://stackoverflow.com/help/someone-answers –

0

あなたは最高でしたが、.reduce

input.reduce((res,x)=>{ 
res[x.type] = res[x.type] || {}; 
res[x.type][x.brand] = res[x.type][x.brand] || {} 
res[x.type][x.brand][x.subBrand]= res[x.type][x.brand][x.subBrand] || {size:[]} 
res[x.type][x.brand][x.subBrand].size.push(x.size) 
return res; 
},{}) 
関連する問題