How to iterate into object method in javascript

Viewed 45

let person = {
  firstName: "Rella",
  lastName: "binson",
  age: 18,
  getFullName: function() {
    return this.firstName + ' ' + this.lastName;
  }
};

for (let key in person) {
  if (person.hasOwnProperty(key)) {
    console.log(key + ' ' + person[key])
  }
}
// it doesn't print 'getFullName()

2 Answers

Here is another way to do it with modern Object.keys() method and collecting them into array

let person = {
  firstName: "Rella",
  lastName: "binson",
  age: 18,
  getFullName: function() {
    return this.firstName + ' ' + this.lastName;
  }
}

const objectMethods = Object.keys(person).filter(item => {
  person.hasOwnProperty(item) &&
  typeof person[item] === 'function'
})
Related