Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to map array of unknown object keys

Now I write it this way:

const array = [
  {name: 'somename', lastname: 'sometext'}
  {name: 'somename1', lastname: 'sometext1'}
  {name: 'somename2', lastname: 'sometext2'}
]

function Component({array}) {
  return (
    {array.map(( {name, lastname} ) => (
      <p>{name}<p>
      <p>{lastname}<p>
    ))}
  )
}

But I want to pass array of objects with any keys:

  {array.map(( {unknownKey, unknownKey1} ) => (
    <p>{unknownKey}<p>
    <p>{unknownKey1}<p>
   ))}

How write it correctly?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If you want to show all values of the objects in <p>s, then map over the Object.values of the object being iterated over (don’t destructure).

const array = [
  {name: 'somename', lastname: 'sometext'},
  {name: 'somename1', lastname: 'sometext1'},
  {name: 'somename2', lastname: 'sometext2'}
];

const Component = ({array}) => (
  array.map(
    object => Object.values(object).map(val => <p>{val}</p>)
  )
);
ReactDOM.createRoot(document.querySelector('.react')).render(<Component {...{ array }} />);
<script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
<div class='react'></div>

It would be nice if you could require the passed objects to have a key (a unique identifier for a given object to be rendered) as well – that way React will be able to re-render them more efficiently.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading