Skip to content Skip to sidebar Skip to footer

Javascript Object Properties - Connect Them Together?

I have 3 objects in an array. myArray = [ {name: 'iPhone', link: 'www.apple.com'}, {name: 'Nokia', link: 'www.nokia.com'}, {name: 'Google', link: 'www.Google.com'} ] How to make a

Solution 1:

With pure JS, it would be like that :

for(var i=0;i<myArray.length;i++){
    var a = document.createElement('a');
    a.href= myArray[i].link;
    a.text= myArray[i].name;
    document.body.appendChild(a);
}

But it is much easier with jQuery:

You can use jQuery .each(). It will loop through your array and you can access object properties with this.

To make a link, you create a a element and assing his value with .attr() and .text()

$.each(myArray, function(){
    var a = $('<a/>'); //The element itself
    a.attr('href', this.link) //The HREF
    a.text(this.name) //The text
    $('body').append(a) //Append to the body
})

Solution 2:

a loop and put properties together to display on page

Sounds like you want to create an html string:

var list = "<ul>";
for (var i=0; i<myArray.length; i++) {
    list += "<li><a href='"+myArray[i].link+"'>"+myArray[i].name+"</a></li>";
}
list += "</ul>";
$("body").html(list); // or something

Solution 3:

You could do something like this:

myArray = [
           {name: "iPhone", link: "www.apple.com"},
           {name: "Nokia", link: "www.nokia.com"},
           {name: "Google", link: "www.Google.com"}
         ];
var myDiv = '<div>';
for(var i=0;i<myArray.length;i++){
    myDiv= myDiv+ '<a href=\"'+myArray[i].link+'\">'+myArray[i].name +'</a><br/>';
}
myDiv = myDiv + '</div>';
$('#someDiv').append(myDiv); // append it to some other div

enjoy!

Post a Comment for "Javascript Object Properties - Connect Them Together?"