0

I am trying to loop through key base objects & trying to access the values which inside each number keys,

How can I loop through key base objects?

Can anyone help me, please?

"links": {
        "1": {
            "name": "website",
            "link": "www.google.com"
        },
        "2": {
            "name": "facebook",
            "link": "www.facebook.com/"
        },
        "3": {
            "name": "instagram",
            "link": "www.instagram.com/"
        },
        "4": {
            "name": "twitter",
            "link": "www.twitter.com"
        },
        "5": {
            "name": "linkedin",
            "link": "www.linkedin.com"
        }
    },
{data.links[].name.map((item) => (
    <div>{item.name}</div>
))}

Thanks in advance

Muhammad Owais
  • 980
  • 3
  • 17
  • 37
  • 3
    Does this answer your question? [How do I loop through or enumerate a JavaScript object?](https://stackoverflow.com/questions/684672/how-do-i-loop-through-or-enumerate-a-javascript-object) - in short, use [`Object.keys`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys), [`Object.entries`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries) or [`Object.values`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/values) and a `.map`. – cbr Jul 10 '20 at 19:57

2 Answers2

1

Try this

{Object.values(data.links).map((item) => (
    <div>{item.name}</div>
))}

Explanation: Object.values(data.links) will return an Array with the value from each key, something like that:

[
  { name: 'website', link: 'www.google.com' },
  { name: 'facebook', link: 'www.facebook.com/' },
  { name: 'instagram', link: 'www.instagram.com/' },
  { name: 'twitter', link: 'www.twitter.com' },
  { name: 'linkedin', link: 'www.linkedin.com' }
]

And than, you'll be able to iterate over that Array with .map and access the name property of each object.

0

You can use Object.keys() function to get an array of keys and use that key and access data:

Object.keys(data.links).map(key => (
    <div>{data.links[key]}</div>
));

This solution is OK if you need the actual key for something else. If you dont need the key you can use Object.values(data.link) and loop directly trough values.

Mario Petrovic
  • 7,500
  • 14
  • 42
  • 62