I have a headless CMC WP that's fetched into my Javascript and stored. I want to filter it by a property(if the property value = to the value I input in html then it should append to the innerHTML) and therefore I tried to loop through it but it does not work. This is my function:
for (let i in this.filtered) {
for (let y in this.filtered[i].categories) {
//console.log(this.filtered[i].categories[y] " ");
const results = this.filtered[i].categories[y].filter(post => post == value)
console.log(results);
}
}
It says in the console that this.filtered[i].categories[y].filter
is not a function.
this is a part of the array from this.filtered
, I want to filter by categories.
This is what it shows when I console.log(this.filtered[i].categories[y]);
Thank you in advance!
CodePudding user response:
It says in the console that
this.filtered[i].categories[y].filter
is not a function.
The items in the categories
array, according to your screenshot, are simple integers. Integers don’t understand/implement any method called filter()
. (Put another way: what would you do if I told you to filter the number 7?) Logically, it’s clear that this is not what you intended.
While you’re headed down the right path, I’d recommend you keep it simple: run Array.filter
on your outermost array and use the logic in the callback to test whether the categories
sub-array contains the value you’re looking for:
var _this = {};
_this.filtered = [{
acf: {},
author: 1,
categories: [18, 2, 3]
},
{
acf: {},
author: 2,
categories: [4, 3, 7, 18]
}
];
const value = 2;
var filteredResults = _this.filtered.filter(cv => cv.categories.includes(value));
console.log(filteredResults);