Javascript javascript过滤对象数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13594788/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 12:26:14  来源:igfitidea点击:

javascript filter array of objects

javascriptjqueryarrays

提问by user441521

I have an array of objects and I'm wondering the best way to search it. Given the below example how can I search for name = "Joe"and age < 30? Is there anything jQuery can help with or do I have to brute force this search myself?

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

var names = new Array();

var object = { name : "Joe", age:20, email: "[email protected]"};
names.push(object);

object = { name : "Mike", age:50, email: "[email protected]"};
names.push(object);

object = { name : "Joe", age:45, email: "[email protected]"};
names.push(object);

回答by VisioN

You may use jQuery.grep():

您可以使用jQuery.grep()

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

DEMO:http://jsfiddle.net/ejPV4/

演示:http : //jsfiddle.net/ejPV4/

回答by lonesomeday

You can do this very easily with the [].filtermethod:

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

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

You will need to add a shim for browsers that don't support the [].filtermethod: this MDN pagegives such code.

您需要为不支持该[].filter方法的浏览器添加一个 shim :这个 MDN 页面提供了这样的代码。

回答by Vadim Gremyachev

You could utilize jQuery.filter()function to return elements from a subset of the matching elements.

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

var names = [
    { name : "Joe", age:20, email: "[email protected]"},
    { name : "Mike", age:50, email: "[email protected]"},
    { name : "Joe", age:45, email: "[email protected]"}
   ];
   
   
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"/>

回答by Fakhrul Hasan

var nameList = [
{name:'x', age:20, email:'[email protected]'},
{name:'y', age:60, email:'[email protected]'},
{name:'Joe', age:22, email:'[email protected]'},
{name:'Abc', age:40, email:'[email protected]'}
];

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

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

You can simply use javascript :)

你可以简单地使用 javascript :)

回答by Arun Kumar Saini

For those who want to filter from an array of objects using any key:

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

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

filter from an array of the JSON objects:**

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

回答by Parth Raval

var names = [{
        name: "Joe",
        age: 20,
        email: "[email protected]"
    },
    {
        name: "Mike",
        age: 50,
        email: "[email protected]"
    },
    {
        name: "Joe",
        age: 45,
        email: "[email protected]"
    }
];
const res = _.filter(names, (name) => {
    return name.name == "Joe" && name.age < 30;

});
console.log(res);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.js"></script>

回答by Cody

So quick question. What if you have two arrays of objects and you would like to 'align' these object arrays so that you can make sure each array's objects are in the order as the other array's? What if you don't know what keys and values any of the objects inside of the arrays contains... Much less what order they're even in?

这么快的问题。如果您有两个对象数组,并且想要“对齐”这些对象数组,以便确保每个数组的对象与另一个数组的对象顺序相同,该怎么办?如果您不知道数组内的任何对象包含哪些键和值怎么办……更不用说它们的顺序了?

So you need a 'WildCard Expression' for your [].filter, [].map, etc. How do you get a wild card expression?

所以,你需要为你一个“通配符表达式” [].filter[].map等你如何获得外卡的表达?

var jux = (function(){
    'use strict';

    function wildExp(obj){
        var keysCrude = Object.keys(obj),
            keysA = ('a["' + keysCrude.join('"], a["') + '"]').split(', '),
            keysB = ('b["' + keysCrude.join('"], b["') + '"]').split(', '),
            keys = [].concat(keysA, keysB)
                .sort(function(a, b){  return a.substring(1, a.length) > b.substring(1, b.length); });
        var exp = keys.join('').split(']b').join('] > b').split(']a').join('] || a');
        return exp;
    }

    return {
        sort: wildExp
    };

})();

var sortKeys = {
    k: 'v',
    key: 'val',
    n: 'p',
    name: 'param'
};
var objArray = [
    {
        k: 'z',
        key: 'g',
        n: 'a',
        name: 'b'
    },
    {
        k: 'y',
        key: 'h',
        n: 'b',
        name: 't'
    },
    {
        k: 'x',
        key: 'o',
        n: 'a',
        name: 'c'
    }
];
var exp = jux.sort(sortKeys);

console.log('@juxSort Expression:', exp);
console.log('@juxSort:', objArray.sort(function(a, b){
    return eval(exp);
}));

You can also use this function over an iteration for each object to create a better collective expression for all of the keys in each of your objects, and then filter your array that way.

您还可以在每个对象的迭代中使用此函数为每个对象中的所有键创建更好的集体表达式,然后以这种方式过滤您的数组。

This is a small snippet from the API Juxtapose which I have almost complete, which does this, object equality with exemptions, object unities, and array condensation. If these are things you need or want for your project please comment and I'll make the lib accessible sooner than later.

这是我几乎完成的 API Juxtapose 的一个小片段,它做到了这一点,具有豁免的对象相等性、对象统一性和数组压缩。如果这些是您的项目需要或想要的东西,请发表评论,我会尽快使库可访问。

Hope this helps! Happy coding :)

希望这可以帮助!快乐编码:)

回答by Kasra Khosravi

The most straightforward and readable approach will be the usage of native javascript filter method.

最简单易读的方法是使用原生 javascript 过滤方法。

Native javaScript filter takes a declarative approach in filtering array elements. Since it is a method defined on Array.prototype, it iterates on a provided array and invokes a callback on it. This callback, which acts as our filtering function, takes three parameters:

本机 javaScript 过滤器在过滤数组元素时采用声明式方法。由于它是在 Array.prototype 上定义的方法,因此它会在提供的数组上进行迭代并对其调用回调。这个回调函数作为我们的过滤函数,需要三个参数:

element— the current item in the array being iterated over

element— 正在迭代的数组中的当前项

index— the index or location of the current element in the array that is being iterated over

index— 正在迭代的数组中当前元素的索引或位置

array— the original array that the filter method was applied on Let's use this filter method in an example. Note that the filter can be applied on any sort of array. In this example, we are going to filter an array of objects based on an object property.

array— 应用过滤器方法的原始数组 让我们在示例中使用此过滤器方法。请注意,过滤器可以应用于任何类型的数组。在此示例中,我们将根据对象属性过滤一组对象。

An example of filtering an array of objects based on object properties could look something like this:

根据对象属性过滤对象数组的示例可能如下所示:

// Please do not hate me for bashing on pizza and burgers.
// and FYI, I totally made up the healthMetric param :)
let foods = [
  { type: "pizza", healthMetric: 25 },
  { type: "burger", healthMetric: 10 },
  { type: "salad", healthMetric: 60 },
  { type: "apple", healthMetric: 82 }
];
let isHealthy = food => food.healthMetric >= 50;

const result = foods.filter(isHealthy);

console.log(result.map(food => food.type));
// Result: ['salad', 'apple']

To learn more about filtering arrays in functions and yo build your own filtering, check out this article: https://medium.com/better-programming/build-your-own-filter-e88ba0dcbfae

要了解有关在函数中过滤数组的更多信息并构建自己的过滤器,请查看这篇文章:https: //medium.com/better-programming/build-your-own-filter-e88ba0dcbfae