按属性对数组中的元素进行分组



我试图从下面的json中过滤相同颜色的对象,每个颜色值都包含两个值(颜色和数值)的组合,但我只想根据颜色进行过滤。

这是我尝试过的

var _ = require('underscore-plus');
var data = [{
"name": "jim",
    "color": "blue 1",
    "age": "22"
}, {
"name": "Sam",
    "color": "blue 2",
    "age": "33"
}, {
"name": "eddie",
    "color": "green 1",
    "age": "77"
},
{
"name": "Dheeraj",
    "color": "blue 3",
    "age": "25"
},
{
"name": "Suraj",
    "color": "green 1",
    "age": "25"
}
];
var result=_.groupBy(data,"color");
console.log(result)

结果应该是具有相同颜色的对象数组。

[{ "name": "jim", "color": "blue 1", "age": "22" },
 { "name": "Sam", "color": "blue 2", "age": "33" },
 { "name": "Dheeraj", "color": "blue 3", "age": "25" }]

[{ "name": "Suraj", "color": "green 1", "age": "25" },
 { "name": "eddie", "color": "green 1", "age": "77" }]

您可以使用Array.prototype.reduce:

对项目进行分组

var data = [{
  "name": "jim",
  "color": "blue 1",
  "age": "22"
}, {
  "name": "Sam",
  "color": "blue 2",
  "age": "33"
}, {
  "name": "eddie",
  "color": "green 1",
  "age": "77"
}, {
  "name": "Dheeraj",
  "color": "blue 3",
  "age": "25"
}, {
  "name": "Suraj",
  "color": "green 1",
  "age": "25"
}];
var result = data.reduce(function(grouped, obj) {
  var key = obj.color.split(' ')[0]; // get the color from the key
  grouped[key] = (grouped[key] || []).concat(obj); // use the existing array or create a new array, add the object to it, and assign it to the grouped object
  
  return grouped; // return the grouped object
}, {});
console.log(result);

可以按颜色分组

var data = [{ "name": "jim", "color": "blue 1", "age": "22" }, { "name": "Sam", "color": "blue 2", "age": "33" }, { "name": "eddie", "color": "green 1", "age": "77" }, { "name": "Dheeraj", "color": "blue 3", "age": "25" }, { "name": "Suraj", "color": "green 1", "age": "25" }],
    grouped = {},
    colors;
data.forEach(function (a) {
    var group = a.color.match(/^[a-z]+/i);
    grouped[group] = grouped[group] || [];
    grouped[group].push(a);			
});
colors = Object.keys(grouped);
colors.forEach(function (color) {
    console.log(color, grouped[color]);
});
.as-console-wrapper { max-height: 100% !important; top: 0; }

您可以使用Jquery.grep(),例如

var result = $.grep(data, function(n){ return n.color == "blue 3" })

简单地使用groupBy函数,详细说明如下:

var result = _.groupBy(data, function(datum) { return datum.color; });

您需要提供一个要使用的函数,该函数将返回用于对元素进行分组的属性,在本例中为color。

如果您想过滤,如问题中提到的,您可以使用下划线filter方法:

var blueOne = _.filter(data, function(datum){ return datum.color == 'blue 1'; });

相关内容

  • 没有找到相关文章

最新更新