1

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?

asked Jun 19, 2018 at 9:53
1
  • if (element.name...) no need for this.array1 Commented Jun 19, 2018 at 9:54

1 Answer 1

2

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

answered Jun 19, 2018 at 10:00

9 Comments

I think changing !element.name.includes(obj.array2[0]) to !obj.array2.includes(element.name) would make more sense as he wantst o remove items from array1 whose name is present in array2.
Thank you! And how do I refrence the element as the parmeter in that forEach function?
Eg this.array1.forEach((element, i) => { then the index of the current element being iterated over is i. (Don't try to mutate an array while iterating over it though)
I still cannot access that object property name inside of an array.
Instead of if(this.array1.element.name.includes(this.array2[0])) {, I tried if(element[i].name.includes(this.array2[0])) { but still doesn't work.
|

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.