在javascript中执行此操作的最佳方法是什么?

时间:2016-05-23 10:45:58

标签: 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]
          }
       }
     }
};

我试着编写代码并且它变得非常复杂,每次检查每个事物是否更早出现。 请指教。

2 个答案:

答案 0 :(得分: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中),那么你可以使用reduce迭代对象的键并构建对象。



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 :(得分: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;
},{})