0

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?

2
  • What keys do you want to show when rendering? All of them, or the ones specifically chosen by the caller of Component, or..? Commented Oct 12, 2022 at 5:30
  • all of them of course Commented Oct 12, 2022 at 5:32

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

cool, this looks simpler than CertainPerformance's answer
0

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

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.