kabugh
kabugh

Reputation: 315

Getting a property of an object within an array

I use Vue.js and have a method that compares a value from one array with a value from another array.

array1:  [{ name: 'test1', somevar: true }, { name: 'test2', somevar: false }]
array2: ['test1', 'test3']

  compare() {
    //I want to access an object property within an array1
    this.array1.forEach((element) => {
      if(this.array1.element.name.includes(this.array2[0])) {
        // if it is true, I would like to remove that compared value from an array 1
        if(this.array2[0] !== -1) {
          var index = this.array1.element.name.indexOf(this.array2[0])
          this.array1.splice(index, 1)
        }
      }

I think this part: this.array1.forEach((element) is incorrect. How can I access property of that object?

Upvotes: 1

Views: 70

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370619

array1 is an array, not an object, so accessing this.array1.element won't work. Simply refrence the element as the parmeter given to forEach instead.

Also, the function passed forEach accepts another argument: the second argument represents the current element's index, so there's no need to search for indexOf.

But, even better than those tweaks, it would be more appropriate to use filter in this situation:

const obj = {
  array1:  [{ name: 'test1', somevar: true }, { name: 'test2', somevar: false }],
  array2: ['test1', 'test3'],
  compare() {
    obj.array1 = obj.array1.filter(({ name }) => (
      !obj.array2.includes(name)
    ))
  }
}
obj.compare();
console.log(obj.array1);

Upvotes: 2

Related Questions