javascript过滤对象数组

IT技术 javascript jquery arrays
2021-02-06 01:53:08

我有一组对象,我想知道搜索它的最佳方法。鉴于以下示例,我如何搜索name = "Joe"age < 30有什么 jQuery 可以帮助的,或者我必须自己暴力搜索吗?

var names = new Array();

var object = { name : "Joe", age:20, email: "joe@hotmail.com"};
names.push(object);

object = { name : "Mike", age:50, email: "mike@hotmail.com"};
names.push(object);

object = { name : "Joe", age:45, email: "mike@hotmail.com"};
names.push(object);
6个回答

现代解决方案Array.prototype.filter()

const found_names = names.filter(v => v.name === "Joe" && v.age < 30);

或者,如果您仍在使用 jQuery,则可以使用jQuery.grep()

var found_names = $.grep(names, function(v) {
    return v.name === "Joe" && v.age < 30;
});

您可以使用以下[].filter方法轻松完成此操作

var filterednames = names.filter(function(obj) {
    return (obj.name === "Joe") && (obj.age < 30);
});

您可以在此 MDN 页面上了解更多相关信息

您可以利用jQuery.filter()函数从匹配元素的子集中返回元素。

var names = [
    { name : "Joe", age:20, email: "joe@hotmail.com"},
    { name : "Mike", age:50, email: "mike@hotmail.com"},
    { name : "Joe", age:45, email: "mike@hotmail.com"}
   ];
   
   
var filteredNames = $(names).filter(function( idx ) {
    return names[idx].name === "Joe" && names[idx].age < 30;
}); 

$(filteredNames).each(function(){
     $('#output').append(this.name);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="output"/>

var nameList = [
{name:'x', age:20, email:'x@email.com'},
{name:'y', age:60, email:'y@email.com'},
{name:'Joe', age:22, email:'joe@email.com'},
{name:'Abc', age:40, email:'abc@email.com'}
];

var filteredValue = nameList.filter(function (item) {
      return item.name == "Joe" && item.age < 30;
});

//To See Output Result as Array
console.log(JSON.stringify(filteredValue));

你可以简单地使用 javascript :)

对于那些想要使用任意键从对象数组中进行过滤的人:

function filterItems(items, searchVal) {
  return items.filter((item) => Object.values(item).includes(searchVal));
}
let data = [
  { "name": "apple", "type": "fruit", "id": 123234 },
  { "name": "cat", "type": "animal", "id": 98989 },
  { "name": "something", "type": "other", "id": 656565 }]


console.log("Filtered by name: ", filterItems(data, "apple"));
console.log("Filtered by type: ", filterItems(data, "animal"));
console.log("Filtered by id: ", filterItems(data, 656565));

从 JSON 对象数组中过滤:**