peterHasemann
peterHasemann

Reputation: 1580

compare property of object within object array in JavaScript

when rendering my HTML I want to check if the isActive property of the current object within my Handlebars loop is true or false. So my array of objects accesses a given url parameter and the properties have to check the bool on their own.

module.exports = (url) => {
  return {
    menu: [{
      href: '/1.1',
      isActive: function() {
        return this.href == url;
      }
    }, {
      href: '/1.2',
      isActive: function() {
        return this.href == url;
      }
    }, {
      href: '/1.3',
      isActive: function() {
        return this.href == url;
      }
    }]
  }
};

As you can see I always have to setup a function for the comparison. I tried to create a function

const isActiveLink = (obj) => {
   return obj.href == url;
}

and in my menu I go for this

isActive: isActiveLink(this);

but when executing this, the object is undefined. Is there a way to keep isActive dynamic, based on the given parameter, in a more clean way?

Upvotes: 0

Views: 55

Answers (1)

Pierre C.
Pierre C.

Reputation: 1430

You cannot reference an simple JS object with this when creating it. You might want to look into how this works in more details. It can be confusing.

A way to do what you want is to create a class like this one:

class MenuItem {
    constructor(href, url) {
        this.href = href
        this.url = url
    }

    isActive() {
        return this.href == this.url;
    }
}

Then you can do your export like this:

module.exports = (url) => {
    return {
        menu: [
            new MenuItem('/1.1', url),
            new MenuItem('/1.2', url),
            new MenuItem('/1.3', url)
        ]
    }
};

Upvotes: 1

Related Questions