JamesG
JamesG

Reputation: 1601

React: getting undefined when accessing array in state

when I console.log(this.state.animal_names) out my state element I get

>(2) [Array(2), Array(2)]

When I expand that, I get

0: (2) ["dogNames", Array(53)]
1: (2) ["catNames", Array(100)]

However when I try and access those, like so:

desiredAnimal = "dogNames";
this.state.animal_names[desiredAnimal];

I get:

undefined

how do I access these so I can loop through the arrays in each category?

Upvotes: 0

Views: 121

Answers (4)

abofazl rasoli
abofazl rasoli

Reputation: 116

Maybe this will fix your issue

    const result = 
    [
      ["dogNames", Array(2)],
      ["catNames", Array(2)]
    ].find(item => item.indexOf("dogNames") >= 0);
    
    
    console.log(result)

Upvotes: 0

Siva Kondapi Venkata
Siva Kondapi Venkata

Reputation: 11011

Convert the Array to Object using Object.fromEntries

const an = Object.fromEntries(this.state.animal_names);
desiredAnimal = "dogNames";
an[desiredAnimal];

Upvotes: 1

joshuaebs
joshuaebs

Reputation: 82

Is your state structured like this? This might be better.

animalNames: {
dogNames: [],
catNames:[]
}

It may be easier to access all dog names if you stored all dog names as a value of your dogNames property in an animalNames object.

Upvotes: 0

kyun
kyun

Reputation: 10294

You can convert your array to object using reduce().

const animal_names = [ ["dog", [1,2,3,4]], ["cat", [1,2,3]]];

const res = animal_names.reduce((acc, cur) => {
  const name = cur[0];
  acc[name] = cur[1];
  return acc;
}, {});

console.log(res.dog);
console.log(res.cat);

Upvotes: 0

Related Questions