0

I am trying to remove each user that does not have a firstName and lastName.

This is the object:

users = [{firstName: "john", lastName: "smith"}, {firstName: "", lastName: ""}]

This is my code:

let users = this.users.map(user => {
        if (user.firstName !== '' && user.lastName !== '') {
          return user
        }
})

It does remove the empty ones, but it replaces it with null, and I want to completely remove it and not display null instead of the object.

What I get when I log it the mapped array: [{firstName: "john", lastName: "smith"}, null]

Holiday
  • 871
  • 1
  • 8
  • 14

2 Answers2

3

You should use a filter, not a map, a map simply applies some transformation on the elements, filter, however, is suitable for removing/keeping elements based on certain conditions:

var users = [{firstName: "john", lastName: "smith"}, {firstName: "", lastName: ""}]

users = users.filter(user => (user.firstName !== '' && user.lastName !== ''));

console.log(users);
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55
1

Use filter() instead:

let users = this.users.filter(user => (user.firstName !== '' && user.lastName !== ''));
DontVoteMeDown
  • 21,122
  • 10
  • 69
  • 105