Home > database >  How to map array of unknown object keys
How to map array of unknown object keys

Time:10-12

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?

CodePudding user response:

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.

CodePudding user response:

you first need to extract all the keys from every object and then extract its value from that object.

{array.map((obj) => {
    const keys = Object.keys(obj)
    return keys.map(key => <p>{obj[key]}</p>);
  })
 }

CodePudding user response:

I suggest a solution is define prop for the key which you want to render

function Component({array, firstKey, secondKey}) {
  return (
    {array.map(( item ) => (
      <p>{item[firstKey]}<p>
      <p>{item[secondKey]}<p>
    ))}
  )
}
  • Related