【发布时间】:2020-11-19 10:13:13
【问题描述】:
我有以下数据:
var groups = {
0: { 'GroupID': 1, 'AttributeID': 'Agitator', 'Value': 'No' },
1: { 'GroupID': 1, 'AttributeID': 'ATG', 'Value': 'Custodian' },
2: { 'GroupID': 1, 'AttributeID': 'Heating Coil', 'Value': 'Mild Steel' },
3: { 'GroupID': 2, 'AttributeID': 'Agitator', 'Value': 'Yes' },
4: { 'GroupID': 2, 'AttributeID': 'ATG', 'Value': 'Non Custodian' },
5: { 'GroupID': 2, 'AttributeID': 'Heating Coil', 'Value': 'Mild Steel' },
};
我想按 GroupID 对数据进行分组,并将其中一个值用作另一个值的键。预期结果如下。这可以实现吗?
var data = {
0: { 'GroupID': 1, 'Agitator': 'No', 'ATG': 'Custodian', 'Heating Coil': 'Mild Steel' },
1: { 'GroupID': 2, 'Agitator': 'Yes', 'ATG': 'Non Custodian', 'Heating Coil': 'Mild Steel' }
};
到目前为止,我尝试过的如下。我不知道如何将一个值作为另一个值的键。
_.chain(groups).groupBy('GroupID').map((value, key) => {
return {
GroupID: key,
AttributeID: _.map(value, 'AttributeID'),
Value: _.map(value, 'Value')
}
}).value();
结果如下所示。
var data = {
0: { 'GroupID': 1, 'AttributeID': ['Agitator', 'ATG', 'Heating Coil'], 'Value': ['No', 'Custodian', 'Mild Steel'] },
1: { 'GroupID': 2, 'AttributeID': ['Agitator', 'ATG', 'Heating Coil'], 'Value': ['Yes', 'Non Custodian', 'Mild Steel'] }
};
感谢任何帮助。
【问题讨论】:
-
您是否尝试过解决您自己的问题,如果有,它是什么样的?您咨询过哪些来源?有没有让您感到困惑的文档?
-
编辑了我的问题以包括我迄今为止尝试过的内容。谢谢。
标签: lodash underscore.js