1

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?

Aziza Kasenova
  • 1,501
  • 2
  • 10
  • 22
  • Does it work if you refactor your map to `const updatedHeaders = headers.map(h => ({ filter: function(value){ return value }, ...h }))`. In this case, if I call `console.log(updatedHeaders[0].filter('value'))`, it prints `value` as expected – Claudio Busatto Mar 10 '21 at 22:26
  • @ClaudioBusatto I refactored accordingly and am still faced with the same error, it may have something to do with using "this" maybe? I need to use "this" in order to access my data in the Vue component – mynameismyname1010101 Mar 10 '21 at 22:38
  • @mynameismyname1010101 I think you need to show a minimal example that demonstrates your problem. Use a boilerplate - https://jsfiddle.net/boilerplate/vue – stdob-- Mar 11 '21 at 00:09

1 Answers1

0

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()))
Josh Lin
  • 2,397
  • 11
  • 21