How do I dynamically add method to javascript object without getting this weird error

225 views Asked by At

I have an array of javascript objects,

let headers = [
  {
    text: 'something',
    value: 'something else'
  },
  {
    text: 'something1',
    value: 'something else1'
  },
  // etc..
]

I want to loop through the array and add a method to each object in the array like so (ignore "this", I'm using vue):

this.headers.map(h => {
    h['filter'] = function (value) {
        if (!this.filterValue) {
            return true;
        }

        return value.toLowerCase().includes(this.filterValue.toLowerCase());
    }
});

It looks fine to me, but when my loop completes, the function does not work, and I think it has something to do with this error in "arguments" and "caller":

my console.log(array) after running the loop

Any ideas on how to resolve this error?

1

There are 1 answers

0
Josh Lin On

the key thing is this, you need to learn more about this in JS, and it is asked in interviews a lot, run this snippet and figure how this is going

function A(headers = [{
    text: 'something',
    value: 'something else'
  },
  {
    text: 'something1',
    value: 'something else1'
  },
  // etc..
], filterValue = 'else1') {
  this.filterValue = filterValue
  this.headers = headers.map(h => ({
    ...h,
    filter: () => {
      if (!this.filterValue) {
        return true;
      }

      return h.value.toLowerCase().includes(this.filterValue.toLowerCase());
    }
  }))
}

console.log(new A().headers.map(x => x.filter()))