0

I have following array of objects in React:

const arr = [
  { randomnumber: 'random string' },
  { randomnumber: 'random string' }
];

Where every number (key) and string (value) are always random. How to render this? I want to get something like this:

<p> {randomnumber} is: {randomstring} </p>

I've tried few methods with map, but it doesn't work. Any ideas?

Raf1k
  • 31
  • 6
  • Please show us your attempts – 0stone0 Nov 30 '22 at 09:52
  • 1
    Does this answer your question? [How to loop through key/value object in Javascript?](https://stackoverflow.com/questions/2958841/how-to-loop-through-key-value-object-in-javascript) – 0stone0 Nov 30 '22 at 10:01

1 Answers1

3

Assuming each object has a single key/value pair, you can use the Object.keys() and Object.values() functions:

arr.map(obj => {
  const [key] = Object.keys(obj);
  const [value] = Object.values(obj);

  return (
    <p key={key}>
      {key} is: {value}
    </p>
  );
});
Arkellys
  • 5,562
  • 2
  • 16
  • 40