Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate into object method in javascript

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()
like image 576
Bena Art Avatar asked Dec 05 '25 14:12

Bena Art


1 Answers

Consider using getter property:

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

for (let key in person) {
  if (person.hasOwnProperty(key)) {
    console.log(key + ' ' + person[key])
  }
}

Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get

like image 108
zmag Avatar answered Dec 08 '25 05:12

zmag



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!