按组将2列合并为1列

时间:2019-02-11 03:00:04

标签: javascript

我有一个包含两个字段的对象数组:CategoryName

我打电话给一个端点,我得到了类似的东西。

+----------+----------+
| Category | Name     |
+----------+----------+
| A        | product1 |
+----------+----------+
| A        | product2 |
+----------+----------+
| A        | product3 |
+----------+----------+
| B        | product4 |
+----------+----------+
| B        | product5 |
+----------+----------+
| C        | product6 |
+----------+----------+
| D        | product7 |
+----------+----------+
| D        | product8 |
+----------+----------+

但是我需要将此数组转换为单列,以使类别排在第一位,然后在同一类别下的名称排在第二位。

这是我要找的结果。

+------------+
| One Column |
+------------+
| A          |
+------------+
| product1   |
+------------+
| product2   |
+------------+
| product3   |
+------------+
| B          |
+------------+
| product4   |
+------------+
| product5   |
+------------+
| C          |
+------------+
| product6   |
+------------+
| D          |
+------------+
| product7   |
+------------+
| product8   |
+------------+

1 个答案:

答案 0 :(得分:1)

您可以使用存储最后一个值的辅助变量来减少项目。

let data = [
  { "Category": "A", "Name": "product1"	},
  { "Category": "A", "Name": "product2"	},
  { "Category": "A", "Name": "product3"	},
  { "Category": "B", "Name": "product4"	},
  { "Category": "B", "Name": "product5"	},
  { "Category": "C", "Name": "product6"	},
  { "Category": "D", "Name": "product7"	},
  { "Category": "D", "Name": "product8"	}
];

console.log(transform(data, 'Category', 'Name'));

function transform(data, categoryField, nameField) {
  let last = null; // Helper
  return data.reduce((result, item) => {
    if (last == null || last[categoryField] != item[categoryField]) {
      result.push(item[categoryField]);
    }
    result.push(item[nameField]);
    last = item; // Update
    return result;
  }, []);
}
.as-console-wrapper { top: 0; max-height: 100% !important; }