skip to Main Content

Is there any way to invoke a method on each property instead of calling it on the obj and giving property as argument?
For example if I have an object like this:

const obj = { person: "John Smith" };

I know I can add a method like the following to the object:

addM(p) { return "Mr. " + p; }

and then call it as:

obj.addM(obj.person)

But is there any way to define the method that can be invoked like:

obj.person.addM()

or even better: obj.person.addM

Sorry if I simplified the question too much, I believe I can figure out how to code what I want in my project if I know the solution of this simple problem.
Actually I have some nested objects so please consider it in answering if necessary.
For example if I have:

const obj = {
  person1: { firstName: "John", lastName: "Smith" },
  person2: ...,
  .
  fullName() {
    return this.firstName + this.lastName;
  }
};

I want to invoke it as obj.person1.fullName

2

Answers


  1. put full name function in your object

    const obj = {
          Name: "John",
          fullName() {
            return `MR ${this.Name}`;
          }
    };
    

    to call new Name

    obj.fullName();
    
    Login or Signup to reply.
  2. You can use Object.defineProperty, As the MDN explain: "The Object.defineProperty() static method defines a new property directly on an object, or modifies an existing property on an object, and returns the object."

    In this example, use Object.defineProperty for every obj child add a new property fullName

    const obj = {
      person1: { firstName: "John", lastName: "Smith" },
      person2: { firstName: "Jane", lastName: "Doe" }
    };
    
    Object.keys(obj).forEach(key => {
      Object.defineProperty(obj[key], 'fullName', {
        get() {
          return `${this.firstName} ${this.lastName}`;
        }
      });
    });
    
    console.log(obj.person1.fullName); // John Smith
    console.log(obj.person2.fullName); // Jane Doe
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search