I made similar question, but it’s not solving my problem. I have an object that I’m getting from API using fetch().
When I console.log() fetched data, I get this for example:
let fetchData = {
type: "string",
id: 123,
included: [
{
type: "wanted-type",
attributes: { stats: { name: "name1" } }
}, {
type: "not-wanted-type",
id: 111
}, {
type: "wanted-type",
attributes: { stats: { name: "name2" } }
}]
}
First I tried to access desired value like this “fetchData.included.find(value => value.attributes.stats.name === “name1) but then I realized not all objects in array have “attributes” key. So I used filter method to gather all objects with type of “wanted-type” into another array and I made it. It looked like this:
let arrayFetch = fetchData.included;
let array = [];
const result = arrayFetch.filter(res => res.type === "wanted-type");
if(result) {
array.push(result);
}
It successfully push desired data into “array”, but when I later try to access anything, it says it’s undefined. For example:
console.log(array[0].attributes) or
console.log(array[0].attributes.stats.name)
it says “undefined”.
Can you please help?
Jasmin Mujcinovic is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.