3

So i have this array of objects :

const arr = [
{
name: "Bob",
job: "Teacher",
age: 30
},
{
name: "Jack",
occupation: "Developer",
height: "160 cm"
}
]

My goal here is to get the property name(for ex : occupation) along with its value dynamically and display both of them using the map function in JS , because am using React to display the data.

(i know there's a way with Object.keys()) , but if there's a way with map it would be better for me

an example of the display for the 1st object would be :

name : bob
job : teacher
age : 30

Thanks in advance !

1
  • 2
    you should use both map and Object.keys(). Commented Dec 18, 2020 at 2:40

3 Answers 3

5

arr.map(user =>
  <div>
    {Object.keys(user).map(key => (
      <div>{key}: {user[key]}</div>
    ))}
  </div>
)
Sign up to request clarification or add additional context in comments.

Comments

1
const arr = [{
    name: "Bob",
    job: "Teacher",
    age: 30
  },
  {
    name: "Jack",
    occupation: "Developer",
    height: "160 cm"
  }
]

return (<div>
  {
    arr.map(person => (<div>
      {Object.keys(person).map(key => 
        <span>{key} : {person[key]}</span>
      }
    </div>)
  }
</div>)

Comments

0

Try something like:

arr.map(el => {
    return {
        name: el.name,
        job: el.job,
        age: el.age
    }
})

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.