Javascript使用键将数组附加到对象中

时间:2018-01-15 21:12:49

标签: javascript arrays object

我有这样的数据:

[{ team: 'Team1',
     wins: 1,
     group: GroupA
},{ team: 'Team2',
     wins: 1,
     group: GroupA
},{ team: 'Team3',
     wins: 1,
     group: GroupB
},{ team: 'Team4',
     wins: 1,
     group: GroupB
}]

我希望以这种形式(我基本上想要按一些值对数据进行分组,在本例中为“group”,并将该值用作数组对象中的键):

{ GroupA: [{'Team1', wins: 1, group: GroupA},{'Team2', wins: 1, group: GroupA}],
GroupB: [{'Team3', wins: 1, group: GroupB},{'Team4', wins: 1, group: GroupB}]
}

我该如何做到这一点?

这是我尝试过的,几乎可以使用的,但返回对象:

var newStats = {}
     arrTeamStats.map(function(key,idx){

                var arr = [];

                if(newStats[key.group] == undefined) {
                    arr = key;
                    newStats[key.group] = arr;
                } else {
                else {
                    group = key.group;
                    newStats[group].push(key);
                }
           }

3 个答案:

答案 0 :(得分:4)

您需要reduce您的数组才能返回Object

arrTeamStats.reduce(function(h, o) {
  h[o.group] = h[o.group] || []
  h[o.group].push(o)
  return h
}, {})

HTH

答案 1 :(得分:1)

首先,你误解了.map()。它不是通用迭代器,而是用于从现有迭代器的内容创建新数组。

您可以做的只是迭代并在找到对象时添加新属性,并整合内容。

var data = [{ team: 'Team1',wins: 1,group: "GroupA"},{ team: 'Team2',wins: 1,group: "GroupA"},{ team: 'Team3',wins: 1,group: "GroupB"},{ team: 'Team4',wins: 1,group: "GroupB"}];

var result = {};
for (const o of data) {
  if (result.hasOwnProperty(o.group)) result[o.group].push([o]);
  else result[o.group] = [[o]];
}

console.log(result);

或者像这样简洁一点:

var data = [{ team: 'Team1',wins: 1,group: "GroupA"},{ team: 'Team2',wins: 1,group: "GroupA"},{ team: 'Team3',wins: 1,group: "GroupB"},{ team: 'Team4',wins: 1,group: "GroupB"}];

var result = {};
for (const o of data) result[o.group] = (result[o.group] || []).concat([[o]]);

console.log(result);

答案 2 :(得分:0)

如果你倾向于使用像Lodash这样的东西,你可以使用_.groupBy,如下所示:



var input = [{ team: 'Team1',
     wins: 1,
     group: 'GroupA'
},{ team: 'Team2',
     wins: 1,
     group: 'GroupA'
},{ team: 'Team3',
     wins: 1,
     group: 'GroupB'
},{ team: 'Team4',
     wins: 1,
     group: 'GroupB'
}];

var output = _.groupBy(input, 'group');
console.log(output);

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
&#13;
&#13;
&#13;