使用对象分组数组项我的数组是这样的:myArray = [
{group: "one", color: "red"},
{group: "two", color: "blue"},
{group: "one", color: "green"},
{group: "one", color: "black"}]我想把它转换成:myArray = [
{group: "one", color: ["red", "green", "black"]}
{group: "two", color: ["blue"]}]所以,基本上,按group.我在努力:for (i in myArray){
var group = myArray[i].group;
//myArray.push(group, {???})}我只是不知道如何处理类似组值的分组。
3 回答
繁花如伊
TA贡献2012条经验 获得超12个赞
for ... in
var groups = {};for (var i = 0; i < myArray.length; i++) { var groupName = myArray[i].group; if (!groups[groupName]) { groups[groupName] = []; } groups[groupName].push(myArray[i].color);}myArray = [];for (var groupName in groups) { myArray.push({group: groupName, color: groups[groupName]});}
groups
groups
for ... in
增编
if
groups[groupName].push(myArray[i].color);
if (!$.inArray(myArray[i].color, groups[groupName])) { groups[groupName].push(myArray[i].color);}
inArray
:
Array.prototype.contains = function(value) { for (var i = 0; i < this.length; i++) { if (this[i] === value) return true; } return false;}
if (!groups[groupName].contains(myArray[i].color)) { groups[groupName].push(myArray[i].color);}
添加回答
举报
0/150
提交
取消