JavaScript中对象数组 根据某个属性值 然后push到新的数组

时间:2021-07-20 16:29:12

原文链接

https://segmentfault.com/q/1010000010075035

将下列对象数组中,工资大于1w的员工,增加到对象数组 WanSalary中

var BaiduUsers = [];
var User = function(id, name, phone, age, salary) {
this.id = id;
this.name = name;
this.phone = phone;
this.age = age;
this.salary = salary;
};
User.create = function(id, name, phone, age, salary) {
return new User(id, name, phone, age, salary);
};
BaiduUsers.push(User.create(1, 'tommy', '1111',18, 10000));
BaiduUsers.push(User.create(2, 'jerry', '2222',28, 10000));
BaiduUsers.push(User.create(3, 'raobin','3333',14, 12000));
BaiduUsers.push(User.create(4, 'binbin','4444',23, 9800));
BaiduUsers.push(User.create(5, 'arthur','5555',22, 10000));

  

第一种 循环遍历,注意一下return user的位置;有的同学不小心,总是只新增了一个对象数据

var WanSalary = [];
WanSalary =myFunction(WanSalary);
function myFunction(user){
for (var i = 0; i < BaiduUsers.length; i++) {
if (BaiduUsers[i].salary >=10000)
{
WanSalary.push(
User.create(
BaiduUsers[i].id,
BaiduUsers[i].name,
BaiduUsers[i].phone,
BaiduUsers[i].gender,
BaiduUsers[i].age,
BaiduUsers[i].salary
)
); } }return user
}

  

第二种用filter方法

var WanSalary2= BaiduUsers.filter(function(item){
return item.salary>=10000;
})  

由用户说第二种有兼容性问题

需要升级为下面代码

Array.prototype.filter = Array.prototype.filter || function(func) {

      var arr = this;
var r = [];
for (var i = 0; i < arr.length; i++) {
if (func(arr[i],i,arr)) {
r.push(arr[i]);
}
}
return r;
} var arr1 = arr.filter(function(item){ return item.age === 2;
})