简体   繁体   中英

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?

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)
        ]
    }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM