1

this is my code in react.

 const [value, setValue] = React.useState<CountriesEntityData | null>({
    id: '',
    name: '',
    regions: [
      {
        id: '',
        name: '',
        districts: [
          {
            id: '',
            name: '',
            locations: [{ id: '', city: '', division: '', street: '' }],
          },
        ],
      },
    ],
  })

I try this code in resolving this problem

value?.regions?.name

can anyone give me tutorial link in dealing in this kind of situation thank you.

2
  • Can you please elaborate more? Which variable name? Where you wanna use it? You wanna use a variable while defining a state or what? Why have you written this code value?.regions?.name ? Commented Oct 14, 2020 at 7:26
  • Do you expect to actually call setValue(null)? If not and with using an initial value, why even allow null (CountriesEntityData | null)? It just makes things more complicated. Commented Oct 14, 2020 at 7:36

3 Answers 3

1

If you just wanna use the first element you can do:

let name = value?.regions?.[0]?.name;

If if you wanna search the object based on an id, then I think there is a find function on the array which you can use like that:

let name = value?.regions?.find((elm) => elm.id == 'myId')?.name;
Sign up to request clarification or add additional context in comments.

Comments

0

a regions in value is array.
and not answer value?.regions?.name .
because regions contains objects and objects contain property ```name'''

Comments

0

for this kind of problems, simply you can use log and see your variable in console

  console.log(your const);

then by looking at your console, easily you can see how to address your array to get your desired result.

Now assuming that you want to extract the nested names in the object, for two arrays inside each other, you should use two MAP which are nested. this can give you the idea:

{ListOfData.map((item, index) => (
  <div key={index}>
    <h1>{item.title}</h1>
    {item.content.map((c, i) => (
      <div key={i}>
        <h3>{c.title}</h3>
        <h3>{c.description}</h3>
        <hr />
      </div>
    ))}
  </div>
))}

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.