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?
1 Answer 1
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);
9 Comments
!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
.forEach
function?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)name
inside of an array.if(this.array1.element.name.includes(this.array2[0])) {
, I tried if(element[i].name.includes(this.array2[0])) {
but still doesn't work.
if (element.name...)
no need forthis.array1