0

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?

1
  • if your state is an object, you can access it like that, but it is an array. Commented Mar 15, 2021 at 5:53

4 Answers 4

1

Convert the Array to Object using Object.fromEntries

const an = Object.fromEntries(this.state.animal_names);
desiredAnimal = "dogNames";
an[desiredAnimal];
Sign up to request clarification or add additional context in comments.

Comments

0

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);

Comments

0

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.

1 Comment

I am saving these names from database. the database is returning json {"dogames": [{},{},{}], "catNames": [{},{},{}]} - how would I best get them to save in the above format? I can edit my answer with proper code if it helps show you how I am saving them ?
0

Maybe this will fix your issue

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.