Wonderboy111
Wonderboy111

Reputation: 57

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]

Upvotes: 0

Views: 3810

Answers (4)

boehm_s
boehm_s

Reputation: 5544

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>';
});

console.log(links);

You can run the snippet and see the result.

OR, in ES6 syntax :

const links = Object.keys(MyObj).map(key => `<a href="/?categories=${key}&type=${MyObj[key]}/">${MyObj[key]}</a>`);

Upvotes: 2

Hristo93
Hristo93

Reputation: 197

If I understand the problem correctly, you should use $.param(). It will transform your object into url string

Upvotes: 0

Bakhtiiar Muzakparov
Bakhtiiar Muzakparov

Reputation: 2438

If I understood you correct. You can achieve what you want as shown below:

//declare variable
var MyObj ={
    "1": "Val_1",
    "2": "Val_2",
    "3": "Val_3",
};   

//declare an array where you are going to store your elements
var newArray = [];
for(key in MyObj){ //loop over keys of MyObj object variable 
//string variable where we concatenate key and value as below
  var str = "/?categories="+ key +"&type="+MyObj[key]+"/";
  newArray.push(str);//we push this string value to the newArray declared outside of the loop
}

console.log(newArray);//to see the result on the console
//let me know if you have more questions in the comments

Upvotes: 1

Khauri
Khauri

Reputation: 3863

That's an Object, not an array.

An array uses this syntax:

var myArr = ["Val_1", "Val_2"]

And you can easily loop through an array using a for loop

var myArray = ["val_1", "val_2"]

for(let i = 0; i < myArray.length; i++){
    let url = "<a href=\"/?categories=" + i +"&type="+myArray[i]+"\">" +myArray[i]+"</a>"
    console.log(url)
}

Upvotes: 0

Related Questions