将对象数组重新格式化为键数组

时间:2018-04-27 18:36:26

标签: javascript arrays google-apps-script reformatting arrayofarrays

所以我对Javascript有点新意,但我试图将startArray重新格式化为endArray。 startArray基本上是一个订单对象数组,它们总是有不同的orderId,但可以有相同的companyId。我基本上是在尝试切换它,因此它基于公司,因此对于每个companyId,都有一系列公司的订单。我一直在修补并尝试解决这个问题,但说实话,我不知道从哪里开始,或者这种操作是否可行。

我正在使用Google Apps脚本,我认为它仍然采用ES5语法,如果可能的话,我宁愿坚持使用vanilla javascript。

var startArray = [
    {"companyId" : 1,
     "orderId" : 25,
     "product" : "productA"
     "quantity" : 2,
     "price" : 10,
    },
    {"companyId" : 1,
     "orderId" : 20,
     "product" : "productB"
     "quantity" : 3,
     "price" : 5,
    },
   {"companyId" : 2,
     "orderId" : 15,
     "product" : "productA"
     "quantity" : 5,
     "price" : 10,
    }
 ]

 var endArray = [ {
      '1' = [{"orderId" : 25,
         "product" : "productA"
         "quantity" : 2,
         "price" : 10,},
         {"orderId" : 20,
          "product" : "productB"
          "quantity" : 3,
          "price" : 5,}
      },{
     '2' = [{"orderId" : 15,
          "product" : "productA"
          "quantity" : 5,
          "price" : 10,
         }]
   }]


 ]

2 个答案:

答案 0 :(得分:1)

如果你的结果是对象而不是数组,那么这应该可以胜任:



var startArray = [
    {"companyId" : 1,
     "orderId" : 25,
     "product" : "productA",
     "quantity" : 2,
     "price" : 10,
    },
    {"companyId" : 1,
     "orderId" : 20,
     "product" : "productB",
     "quantity" : 3,
     "price" : 5,
    },
   {"companyId" : 2,
     "orderId" : 15,
     "product" : "productA",
     "quantity" : 5,
     "price" : 10,
    }
 ];

var ret = {}

startArray.forEach(company => {
  if (!ret[company.companyId]) {
    ret[company.companyId] = [];
  }
  
  ret[company.companyId].push(company);
});

console.log(ret);




如果您没有ES6支持,只需使用经典for in周期而不是forEach

答案 1 :(得分:1)

使用像reduce之类的东西来创建一个新对象,如果它已经不存在,则插入一个数组作为companyId的键:



function reduce(arr, callback, initialVal) {
  var accumulator = (initialVal === undefined) ? undefined : initialVal;
  for (var i = 0; i < arr.length; i++) {
    if (accumulator !== undefined)
      accumulator = callback.call(undefined, accumulator, arr[i], i, this);
    else
      accumulator = arr[i];
  }
  return accumulator;
}

var startArray = [
  {"companyId" : 1,
   "orderId" : 25,
   "product" : "productA",
   "quantity" : 2,
   "price" : 10,
  },
  {"companyId" : 1,
   "orderId" : 20,
   "product" : "productB",
   "quantity" : 3,
   "price" : 5,
  },
  {"companyId" : 2,
   "orderId" : 15,
   "product" : "productA",
   "quantity" : 5,
   "price" : 10,
  }
];

var endObj = reduce(startArray, function (accum, item) {
  var companyId = item.companyId;
  if (!accum[companyId]) accum[companyId] = [];
  delete item.companyId;
  accum[companyId].push(item);
  return accum;
}, {});
console.log(endObj);
&#13;
&#13;
&#13;