Home > Software design >  render object with map() and JSX - React
render object with map() and JSX - React

Time:07-11

I have an object:

const data = {
  1: "apples",
  2: "bananas",
  3: "cherries"
}

I want to run through this items and use them in rendering JSX. If it was typical array I would use map() but now it gives me an error :

"Property 'map' doesnot exists..."

what can I do in this case? thank you in advance

CodePudding user response:

You could consider using Object.values to turn an object into an array before mapping it to UI

const data = {
  1: "apples",
  2: "bananas",
  3: "cherries"
}

console.log(Object.values(data))

CodePudding user response:

for (const key in data) {
    console.log(`${key}: ${data[key]}`);
}

good to know

Object.keys(data) will get you array of keys -> ['1', '2', '3']

Object.values(data)will get you array of values -> ['apples', 'bananas', 'cherries']

CodePudding user response:

Yeah, it is giving you that error since map() method can only be run on arrays and data is an object.

Rather change your code to

Object.entries(data).map(([key, value]) => console.log(key, value))

For fetching only the keys

Object.keys(data).map(key => console.log(key))

For fetching only the values

Object.values(data).map(value => console.log(value))

CodePudding user response:

You could use Object.entries

return (
        <div>
            {
                Object.entries(data).map(([key, value]) => {
                    <p>{key}: {value}</p>
                })
            }
        </div>
    );
  • Related