如何使用lodash过滤对象数组的数据

时间:2016-08-25 05:29:46

标签: javascript filter lodash

var brands = [];
brands = [null, {
  "id": "1",
  "image": "/images/brands/surf_excel.png",
  "name": "Surf Excel",
  "productCount": "6"
}, {
  "id": "2",
  "image": "/images/brands/rin.png",
  "name": "Rin",
  "productCount": "5"
}, {
  "id": "3",
  "image": "/images/brands/ariel.png",
  "name": "Ariel",
  "productCount": "4"
}];

现在我想得到id = 3的名字。我试过

var data = _.filter(brands, { 'id': 3 });
console.log(data.name);

但它的给定错误无法读取未定义的属性。假设id = 3只有一条记录,任何人都可以帮助我。如何从上面结构中的给定id获取名称。

如果有更好的方法可以获得相同的结果,也值得赞赏。

3 个答案:

答案 0 :(得分:6)

使用原生JavaScript Array#find 方法。



var brands = [];
brands = [null, {
  "id": "1",
  "image": "/images/brands/surf_excel.png",
  "name": "Surf Excel",
  "productCount": "6"
}, {
  "id": "2",
  "image": "/images/brands/rin.png",
  "name": "Rin",
  "productCount": "5"
}, {
  "id": "3",
  "image": "/images/brands/ariel.png",
  "name": "Ariel",
  "productCount": "4"
}];

var data = brands.find(function(v) {
  return v && v.id == "3";
});

console.log(data.name);




检查polyfill option for find method旧浏览器。

如果您想过滤掉数组,请使用 Array#filter 方法。



var brands = [];
brands = [null, {
  "id": "1",
  "image": "/images/brands/surf_excel.png",
  "name": "Surf Excel",
  "productCount": "6"
}, {
  "id": "2",
  "image": "/images/brands/rin.png",
  "name": "Rin",
  "productCount": "5"
}, {
  "id": "3",
  "image": "/images/brands/ariel.png",
  "name": "Ariel",
  "productCount": "4"
}];

var data = brands.filter(function(v) {
  return v && v.id == "3";
});

console.log(data[0].name);




<小时/> 更新: 根据文档使用_.matches进行属性值比较,为您提供了一个对象作为第二个参数。在您的数组id属性中包含一个字符串值,但您在过滤器中提供了一个数字,只需将其更改为字符串将使其工作或使用@Satpal答案中的回调函数。

&#13;
&#13;
var brands = [];
brands = [null, {
  "id": "1",
  "image": "/images/brands/surf_excel.png",
  "name": "Surf Excel",
  "productCount": "6"
}, {
  "id": "2",
  "image": "/images/brands/rin.png",
  "name": "Rin",
  "productCount": "5"
}, {
  "id": "3",
  "image": "/images/brands/ariel.png",
  "name": "Ariel",
  "productCount": "4"
}];
var data = _.filter(brands, {
  'id': "3"
});
console.log(data);
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.js"></script>
&#13;
&#13;
&#13;

答案 1 :(得分:6)

正如您指定并使用_.filter()方法一样。您可以使用pass谓词,它可以是每次迭代将调用的函数。请注意,它会返回一个数组。

var data = _.filter(brands, function(brand){
   return brand != null && brand.id == 3;
});
console.log(data[0].name);

如果您只想使用一个元素_.find()

var data = _.find(brands, function(brand){
   return brand != null && brand.id == 3;
});
console.log(data.name);

答案 2 :(得分:0)

除了使用filter()代替find()之外,您实际上非常接近。您没有看到任何结果的原因是因为对象断言您可以传递给find() / filter()执行严格的相等比较。意思是,3 === '3'将评估为假。