JavaScript 如何根据属性筛选对象数组

JavaScript 如何根据属性筛选对象数组

可以使用JavaScript中的 filter() 函数根据属性筛选对象数组。该 filter() 函数将返回一个新数组,其中包含所有通过给定条件的数组元素。如果没有元素通过条件,则返回一个空数组。该 filter() 函数循环或迭代每个数组元素,并将每个元素传递给回调函数。

语法:

let newArray = array.filter(function(item)
 {
      return conditional_statement;
 });
HTML

注意: filter() 函数不会改变原始数组。

示例1: 我们创建一个“students”的数组,并在数组上调用 filter() 函数,以从满足给定条件的数组中派生元素。

let obj = {
    'Students': [{
        "name": "Raj",
        "Age": "15",
        "RollNumber": "123",
        "Marks": "99",

    }, {
        "name": "Aman",
        "Age": "14",
        "RollNumber": "223",
        "Marks": "69",
    },
    {
        "name": "Vivek",
        "Age": "13",
        "RollNumber": "253",
        "Marks": "89",
    },
    ]
};

let newArray = obj.Students.filter(function (el) {
    return el.Age >= 15 &&
        el.RollNumber <= 200 &&
        el.Marks >= 80;
}
);
console.log(newArray);
HTML

输出: 在对数组应用过滤函数之后,我们得到数组的第一个元素作为输出,因为它满足给定条件。

[{…}]
0
:{name: 'Raj', Age: '15', RollNumber: '123', Marks: '99'}
length
:1
[[Prototype]]
:Array(0)
HTML

示例2: 下面的示例显示了如何从数组中过滤无效条目。我们创建一个“id”的数组,并在数组上调用 filter() 函数,以获取值为非零和数值的“id”。

let array = [
    { id: 3 },
    { id: -1 },
    { id: 0 },
    { id: 15 },
    { id: 12.2 },
    {},
    { id: null },
    { id: NaN },
    { id: 'undefined' }
]

let countInvalidEntries = 0

function filterById(obj) {
    if (Number.isFinite(obj.id) && obj.id !== 0) {
        return true
    }
    countInvalidEntries++
    return false;
}

let arrayById = array.filter(filterById);

console.log('Filtered Array with non-zero and numeric id: \n',
    arrayById);

console.log('Number of Invalid Entries = ', countInvalidEntries);
HTML

输出: 在对大小为9的数组应用 filter() 函数之后,我们得到4个有效(非零和数值)的 id 和5个无效的 id

Filtered Array with non-zero and numeric id: 
 (4) [{…}, {…}, {…}, {…}]
Number of Invalid Entries =  5
HTML

阅读更多:JavaScript 教程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册