Home > front end >  How to access then name property of an object in an array
How to access then name property of an object in an array

Time:11-02

After some research I found out the way to access this Array through mapping would be something like

const locations = [
    {
      country: "United States",
      city: "Henderson",
      state: "Kentucky",
      postalCode: 42420,
    
    },
    {
     
      country: "United States",
      city: "Henderson",
      state: "Kentucky",
      postalCode: 42420,
     
    }]

locations.map((item)=>{<p>{item.city}</p>})

Suppose for the above case I want to get the name such as country ,city eh how do I go about to extract those object titles . I have gone through several documentations and resources but i have not found a clear solution

CodePudding user response:

in the map you should return the object by the removing the curly brackets

locations.map(item => <p>{item.city}</p> )

or if you keep the curly brackets add an explicit return

locations.map(item => { return <p>{item.city}</p> })

If you would like to add more to what is displayed on the page you can add more fields in the map's return

locations.map(item => <p>{item.country}, {item.city}, {item.state}, {item.postalCode}</p> )

CodePudding user response:

I think you mean you would like to use the property names as labels? If so you'll need to iterate the Object.keys() or Object.entries() of each item as a nested map() call. You'll need a containing component to hold it, here an outer <div> element.

const locations = [
  {
    country: 'United States',
    city: 'Henderson',
    state: 'Kentucky',
    postalCode: 42420,
  },
];

locations.map((item) => {
  <div key={item.unique_property}>
    {Object.entries(item).map((label, value) => (
      <p><span>{label}: </span>{value}</p> 
    ))}
  </div>;
});

Which will output something like the following

<div>
  <p><span>country: </span>United States</p>
  <p><span>city: </span>Henderson</p>
  <p><span>state: </span>Kentucky</p>
  <p><span>postalCode: </span>42420</p>
</div>

CodePudding user response:

Below should work didn't tested though .

{locations.map((val) =>
    Object.keys(val?.fields).map((field) => (
      <p key={field}>
        Key : {field}
        Value:{val?.fields[field]}
      </p>
    ))
  )}
  • Related