Home > Software design >  Map over Object to get links in React
Map over Object to get links in React

Time:04-22

I have an API request that comes back with.

externalLinks : {
      website: {
        _links: {
          self: {
            rel: 'self',
            method: 'get',
            href: 'http://www.example.com/',
          },
        },
      },
      twitter: {
        _links: {
          self: {
            rel: 'self',
            method: 'get',
            href: 'https://twitter.com/',
          },
        },
      },
      discord: {
        _links: {
          self: {
            rel: 'self',
            method: 'get',
            href: 'https://discord.gg/',
          },
        },
      }
    };

and in my render I want to generate a link for each of the external links.

<div>
{ // Loop in here to generate links }
</div>

Whats the best way?

CodePudding user response:

You can try something like this with Object.entries

https://developer.mozilla.org/enUS/docs/Web/JavaScript/Reference/Global_Objects/Object/entries

const obj = {
  website: {
    _links: {
      self: {
        rel: "self",
        method: "get",
        href: "http://www.example.com/",
      },
    },
  },
  twitter: {
    _links: {
      self: {
        rel: "self",
        method: "get",
        href: "https://twitter.com/",
      },
    },
  },
  discord: {
    _links: {
      self: {
        rel: "self",
        method: "get",
        href: "https://discord.gg/",
      },
    },
  },
};

const arr = [];
for (const [key, value] of Object.entries(obj)) {
  arr.push({ ["website"]: value._links.self.href });
}

console.log(
  "websites",
  arr.map((item) => item.website)
);

CodePudding user response:

I'd do something like the following:

const links = (
  <div>
    <ul>
      {
        Object.entries(exLinks).reduce((str, [website, val]) => 
          str  = `<a href='${val._links.self.href}'>${website}</a>`, 
        '')
      }
    </ul>
  </div>
); 

If you're specifically looking to use the map function, you can do that too:

let element = (
  <div>
    {Object.entries(exLinks).map(entry => 
      `<a href='${entry[1]._links.self.href}'>${entry[0]}</a>`
    )}
  </div>
)
  • Related