javascript - 基于条件的数组操作JS

标签 javascript arrays json

我有以下数组

0: {productid: "001", containersize: "20", ContCount: 10}
1: {productid: "002", containersize: "20", ContCount: 9}
2: {productid: "001", containersize: "40", ContCount: 4}
3: {productid: "001", containersize: "20", ContCount: 20}
4: {productid: "003", containersize: "20", ContCount: 18}
5: {productid: "001", containersize: "40", ContCount: 7}
6: {productid: "003", containersize: "40", ContCount: 25}

基于这个数组,我想创建一个如下所示的新数组:

0: {productid: "001", containersize20: 30, containersize40: 11, total: 41}
1: {productid: "002", containersize20: 9, containersize40: 0, total: 9}
2: {productid: "003", containersize20: 18, containersize40: 25, total: 43}

基本上,根据产品类型和容器尺寸 20 和 40 计算所有容器。

我使用了下面的代码:

var group_to_values = data.reduce(function (obj, item) {
            obj[item.productid] = obj[item.productid] || [];
            obj[item.productid].push(item.ContCount);
            return obj;
        }, {});

        var groups = Object.keys(group_to_values).map(function (key) {
            return {productid: key, ContCount: group_to_values[key]};
        });

但从这里开始,我陷入了如何进一步前进的困境。

最佳答案

这非常适合reduce。根据您的规范迭代构建映射到键的结果对象的结构,然后获取值数组:

const data = [
  {productid: "001", containersize: "20", ContCount: 10},
  {productid: "002", containersize: "20", ContCount: 9},
  {productid: "001", containersize: "40", ContCount: 4},
  {productid: "001", containersize: "20", ContCount: 20},
  {productid: "003", containersize: "20", ContCount: 18},
  {productid: "001", containersize: "40", ContCount: 7},
  {productid: "003", containersize: "40", ContCount: 25}
];

const res = Object.values(data.reduce((a, e) => {
  if (!(e.productid in a)) {
    a[e.productid] = {
      productid: e.productid, 
      containersize20: 0,
      containersize40: 0,
      total: 0
    };
  }
  
  a[e.productid].containersize20 += e.containersize === "20" ? e.ContCount : 0;
  a[e.productid].containersize40 += e.containersize === "40" ? e.ContCount : 0;
  a[e.productid].total += e.ContCount;
  return a;
}, {}));

console.log(res);

关于javascript - 基于条件的数组操作JS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53492576/

相关文章:

javascript - 将上一页中单击的元素 html 添加到下一页上的另一个元素

javascript - 我无法从 this.state 获取数据

javascript - 纯 javascript - 创建我自己的淡出功能

php - 如何从 PHP 中的单个数组中提取 3 个唯一值?

json - 在 Google 电子表格中导入带有身份验证的 JSON(营销事件监视器)

javascript - Bootstrap 3 - 使用 json 加载表中的链接

java - 如何在 Java 中将包含字符串列表的 JsonNode 转换为逗号分隔的字符串

java - 将数组送入线程

android - 如何使用 JsonArray 的 gson 创建模型类,其中数组是变量而不是常量 android

javascript - 在javascript中将具有嵌套路径和数组的表单序列化为JSON