Generic Technology
Generic Technology

Reputation: 23

how to call variable name in array of object in React

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.

Upvotes: 1

Views: 1324

Answers (3)

garzj
garzj

Reputation: 3254

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;

Upvotes: 1

behzad
behzad

Reputation: 857

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

Upvotes: 0

A.R.SEIF
A.R.SEIF

Reputation: 873

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

Upvotes: 0

Related Questions