Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display data in a React component from an object where the keys are different but the values are the same

I have some data that is in JSON format where the keys are different, but the objects nested inside have a keys that are the same (in this case I want a title and a description).

How do I display this data in a React component?

I've seen that you can 'map' through items in an object similar to how you would in an array using Object.keys(objectName).map() however since the keys at the next level are all unique, I'm not sure how to go down to the next level to get to the data I need.

The JSON data I'm working with looks something like this:

const data = {
  dataINeed: {
    firstObject: {
      id: 'one',
      title: 'First title',
      description: 'First description',
    },
    secondObject: {
      id: 'two',
      title: 'Second title',
      description: 'Second description',
    },
    thirdObject: {
      id: 'three',
      title: 'Third title',
      description: 'Third description',
    },
  },
};

And 'mapping' through the data in React looks something like this:

{Object.keys(data.dataINeed).map((data) => {
  return (
    <dl>
      <dt>{data.*.title}</dt>
      <dd>{data.*.description}</dd>
    </dl>
  );
})}

Which obviously doesn't work as I can't use a wildcard selector.

Any suggestions on how to get to that next level of data?

like image 743
Luke Bennett Avatar asked Jan 19 '26 03:01

Luke Bennett


1 Answers

where the keys are different but the values are the same

Just use Object.values() directly.

{
  Object.values(data.dataINeed).map((data) => (
    <dl key={data.id}>
      <dt>{data.title}</dt>
      <dd>{data.description}</dd>
    </dl>
  ))
}

SAMPLE JS

 const a = {
  dataINeed: {
    firstObject: {
      id: 'one',
      title: 'First title',
      description: 'First description',
    },
    secondObject: {
      id: 'two',
      title: 'Second title',
      description: 'Second description',
    },
    thirdObject: {
      id: 'three',
      title: 'Third title',
      description: 'Third description',
    },
  }
}

console.log(Object.values(a.dataINeed))
like image 165
Joseph D. Avatar answered Jan 21 '26 20:01

Joseph D.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!