Wonderboy111 Wonderboy111 - 1 year ago 71
Javascript Question

display key and value from object and convert into html links

I'm trying to take the key and values from an array and convert it to a list of links.

This is my variable

var MyObj = [{
"1": "Val_1",
"2": "Val_2",
"3": "Val_3",

This is how I'm trying to get the links to look like

<a href="/?categories='+ MyObj[0].key +'&type='+MyObj[0].value+'/">MyObj[0].value</a>

I've been trying various methods but to no concrete result, the closest I came was and output in the console.log that state [Object object]

Answer Source

If you want to get the keys of an Object, you should use Object.keys method.

Then you can loop over your object's keys and build your links. In order to return an array of links, it's better to use the Array#map method :

var MyObj = {
    "1": "Val_1",
    "2": "Val_2",
    "3": "Val_3",

var links = Object.keys(MyObj).map(function(key) {
  return '<a href="/?categories='+ key + '&type=' + MyObj[key] + '/">' + MyObj[key] + '</a>';


You can run the snippet and see the result.

OR, in ES6 syntax :

const links = Object.keys(myObj).map(key => `<a href="/?categories=${MyObj[0].key}&type=${MyObj[0].value}/">${MyObj[0].value}</a>`;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download