Search code examples
arraysnested

Accessing value of specific arrayed objects that are fetched from API - javascript


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?


Solution

  • Observe what result and array are after this:

    const result = arrayFetch.filter(res => res.type === "wanted-type");
    if(result) {
      array.push(result);
    }
    

    Since result is an array, then array is an array of arrays. So this won't work:

    console.log(array[0].attributes)
    

    Because an array has no property called attributes. This could work:

    console.log(array[0][0].attributes)
    

    But instead of digging into the structure you have, use a better structure. Why push result into a new array in the first place? Just use result directly:

    let arrayFetch = fetchData.included;
    const result = arrayFetch.filter(res => res.type === "wanted-type");
    console.log(result[0].attributes);