javascript - 按属性

时间:2016-11-04 20:01:19

标签: javascript arrays mapreduce underscore.js javascript-objects

我试图从下面的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" }]

4 个答案:

答案 0 :(得分:1)

您可以使用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);




答案 1 :(得分:0)

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

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

答案 2 :(得分:0)

只需使用下划线文档here详细说明的groupBy函数:

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

您需要提供一个要使用的函数,它将返回属性以对元素进行分组,在这种情况下为颜色。

如果您想要过滤,如问题中所述,您可以使用下划线filter方法:

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

答案 3 :(得分:0)

您可以按颜色分组。



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; }