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

Dev*_*wal 3 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"
}];
Run Code Online (Sandbox Code Playgroud)

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

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

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

如果有更好的方法来获得相同的结果,也值得赞赏.

Pra*_*lan 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);
Run Code Online (Sandbox Code Playgroud)

检查polyfill选项以查找旧浏览器的查找方法.


如果要过滤掉数组,请使用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);
Run Code Online (Sandbox Code Playgroud)


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

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);
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.js"></script>
Run Code Online (Sandbox Code Playgroud)


Sat*_*pal 6

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

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

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

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