JavaScript 如何根据属性来过滤对象数组

JavaScript 如何根据属性来过滤对象数组

可以使用JavaScript中的 filter() 函数根据属性来过滤对象数组。 filter() 函数会返回一个新数组,其中包含所有满足给定条件的数组元素。如果没有元素满足条件,则返回一个空数组。 filter() 函数会循环遍历每个数组元素,并将每个元素传递给回调函数。

语法:

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

注意: 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);

输出: 在对数组应用筛选函数之后,我们将数组的第一个元素作为输出结果,因为它满足给定的条件。

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

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

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

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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程