Home > Blockchain >  How to render array of objects with random key and values in React?
How to render array of objects with random key and values in React?

Time:12-01

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?

CodePudding user response:

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