2016-05-23 121 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; 
},{}) 
相关问题