使用对象分组数组项 [英] Group array items using object

查看:87
本文介绍了使用对象分组数组项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数组是这样的:

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"]}
]

所以,基本上,按分组

我正在尝试:

for (i in myArray){
  var group = myArray[i].group;
  //myArray.push(group, {???})
}

我只是不知道如何处理类似组值的分组。

I just don't know how to handle the grouping of similar group values.

推荐答案

首先,在JavaScript中它通常不是最好使用中迭代数组。请参阅为什么使用for。 ..in"数组迭代是一个坏主意?了解详情。

First, in JavaScript it's generally not a good idea to iterate over arrays using for ... in. See Why is using "for...in" with array iteration a bad idea? for details.

所以你可以尝试这样的事情:

So you might try something like this:

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 object here有助于加快速度,因为它允许您避免嵌套循环来搜索数组。另外,因为 groups 是一个对象(而不是一个数组),使用 for ...在中迭代它是合适的。

Using the intermediary groups object here helps speed things up because it allows you to avoid nesting loops to search through the arrays. Also, because groups is an object (rather than an array) iterating over it using for ... in is appropriate.

附录

FWIW,如果你想避免重复的颜色条目结果数组你可以在行 groups [groupName] .push(myArray [i] .color); if 语句$ c>防止重复。使用jQuery看起来像这样;

FWIW, if you want to avoid duplicate color entries in the resulting arrays you could add an if statement above the line groups[groupName].push(myArray[i].color); to guard against duplicates. Using jQuery it would look like this;

if (!$.inArray(myArray[i].color, groups[groupName])) {
  groups[groupName].push(myArray[i].color);
}

如果没有jQuery,你可能想要添加一个与jQuery相同功能的函数 inArray

Without jQuery you may want to add a function that does the same thing as jQuery's 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);
}

请注意,无论哪种情况,你都会因为所有额外的迭代,所以如果您不需要避免结果数组中的重复颜色条目,我建议避免使用这些额外的代码。那里

Note that in either case you are going to slow things down a bit due to all the extra iteration, so if you don't need to avoid duplicate color entries in the result arrays I would recommend avoiding this extra code. There

这篇关于使用对象分组数组项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆