过滤器在循环对象的属性(对象数组)时返回一个空数组

时间:2019-08-21 18:13:59

标签: javascript arrays loops object filter

当我尝试遍历对象的array属性时,我不明白为什么filter会返回一个空数组。

但是,当我尝试在getFilteredUsers方法中执行console.log(this.users)时,我可以在其原型中看到filter方法...

var userService = {
  currentFilter: "active",
  users: [
    { name: "Alex", status: "active" },
    { name: "Nick", status: "deleted" }
  ],
  getFilteredUsers: function() {
    // console.log(this.users);
    return this.users.filter(function(user) {
      return user.status === this.currentFilter;
    });    
  }
};

console.log(userService.getFilteredUsers()); // []

2 个答案:

答案 0 :(得分:1)

这是因为

的值
  

这个

在过滤器回调中。使用箭头功能为此获取正确的值

var userService = {
  currentFilter: "active",
  users: [
    { name: "Alex", status: "active" },
    { name: "Nick", status: "deleted" }
  ],
  getFilteredUsers: function() {
    // console.log(this.users);
    return this.users.filter((user)=> {
      return user.status === this.currentFilter;
    });    
  }
};

console.log(userService.getFilteredUsers()); // []

答案 1 :(得分:1)

问题在于对象的范围。它会在 filter()回调函数内部更改。您可以尝试两种方式:

  1. 在过滤器回调函数之前的函数中创建一个新的过滤器变量,例如:

var userService = {
    currentFilter: "active",
    users: [{
            name: "Alex",
            status: "active"
        },
        {
            name: "Nick",
            status: "deleted"
        }
    ],
    getFilteredUsers: function() {
        const currentStatus = this.currentFilter;
        return this.users.filter(function(user) {
            return user.status === currentStatus;
        });
    }
};

console.log(userService.getFilteredUsers()); //[ { name: 'Alex', status: 'active' } ]

  1. 使用es6 箭头功能:

var userService = {
    currentFilter: "active",
    users: [{
            name: "Alex",
            status: "active"
        },
        {
            name: "Nick",
            status: "deleted"
        }
    ],
    getFilteredUsers: function() {
        return this.users.filter(({
            status
        }) => status === this.currentFilter);
    }
};

console.log(userService.getFilteredUsers()); // [ { name: 'Alex', status: 'active' } ]

希望这会有所帮助:)