我对Javascript很新,而且映射有点令人困惑,需要一些帮助。我有一个对象数组的记录集,每个对象具有相同的名称,但对象中的其他3个元素是不同的。该数组看起来像这样
[ { Name: 'MyGroupName',
App_Name: 'App Name 1',
App_ID: '1',
App_Members: 32 },
{ Name: 'MyGroupName',
CI_Name: 'App Name 2',
Apps_ID: '2',
App_Members: 96 },
{ Name: 'MyGroupName',
CI_Name: 'App Name 3',
Apps_ID: '2',
App_Members: 348 }
]
我希望使用名称将他们组合在一起,所以当在屏幕上显示时,我不会反复重复这个名字。所以我需要让我的返回数组看起来像这样
let example = {
'MyGroupName': [
{
App_Name: 'App Name 1',
App_ID: '1',
App_Members: 32
},
{
CI_Name: 'App Name 2',
Apps_ID: '2',
App_Members: 96
},
{
CI_Name: 'App Name 3',
Apps_ID: '2',
App_Members: 348
}
]
我已经开始使用下面的代码,但是我碰到了一堵砖墙而且让我很困惑,任何帮助都会受到赞赏。
.then(function (recordSet) {
let groupToArrayOfApps = {}
for(let record in recordSet) {
// todo: add group name as key to the map & app name to array of apps
}
答案 0 :(得分:0)
您可以使用对象作为结果,并删除对象副本中的属性Name
。
var data = [{ Name: 'MyGroupName', App_Name: 'App Name 1', App_ID: '1', App_Members: 32 }, { Name: 'MyGroupName', CI_Name: 'App Name 2', Apps_ID: '2', App_Members: 96 }, { Name: 'MyGroupName', CI_Name: 'App Name 3', Apps_ID: '2', App_Members: 348 }],
grouped = Object.create(null);
data.forEach(function (a) {
var o = Object.assign({}, a);
delete o.Name;
grouped[a.Name] = grouped[a.Name] || [];
grouped[a.Name].push(o);
});
console.log(grouped);
如果您不介意改变原始对象,可以使用不复制属性的版本,只删除不需要的属性Name
。
var data = [{ Name: 'MyGroupName', App_Name: 'App Name 1', App_ID: '1', App_Members: 32 }, { Name: 'MyGroupName', CI_Name: 'App Name 2', Apps_ID: '2', App_Members: 96 }, { Name: 'MyGroupName', CI_Name: 'App Name 3', Apps_ID: '2', App_Members: 348 }],
grouped = Object.create(null);
data.forEach(function (a) {
grouped[a.Name] = grouped[a.Name] || [];
grouped[a.Name].push(a);
delete a.Name;
});
console.log(grouped);
答案 1 :(得分:0)
现在您只需要检查record.Name
groupToArrayOfApps
作为属性
let recordSet = [ { Name: 'MyGroupName',
App_Name: 'App Name 1',
App_ID: '1',
App_Members: 32 },
{ Name: 'MyGroupName',
CI_Name: 'App Name 2',
Apps_ID: '2',
App_Members: 96 },
{ Name: 'MyGroupName',
CI_Name: 'App Name 3',
Apps_ID: '2',
App_Members: 348 }
];
let groupToArrayOfApps = {};
recordSet.forEach(function(record){
// Check if property already exists, if not add it as empty array
if(!groupToArrayOfApps[record.Name]) groupToArrayOfApps[record.Name] = [];
// Prepare the record to be added (without Name property)
let addRecord = Object.assign({}, record);
// Add the desired record to the property array
groupToArrayOfApps[record.Name].push(addRecord);
});
console.log(groupToArrayOfApps);