Jump to content

jquery .each() within a json array .


netpumber

Recommended Posts

Hi!

 

Server sends such a json object:

{"status":1,"recId":"PL-17534","collectionDate":"08-04-2014","collectorsName":"asdf","donorsName":"","sciName":"asdf","family":"asdf","comName":"asdf","variety":"","area":"asdf","photoFiles":["1.jpg","internet.jpg"]}

So i want to change the html content of an element , by customizing the contents of json object in the photoFiles array.

 

I tried something like this but doesn't seem to work

 

$('#photosTab').html(function(){
    $.each(json.photoFiles, function(i,item){
    return '<img src="'+json.photoFiles[0]+'"><br>';
    })
});

Any idea ?

 

Link to comment
Share on other sites

  • 4 weeks later...

You probably want something like:

//  Renders a single item as html
var renderItem = function (item) {
  return '<img src="' + encodeURI(item) + '">'
}

//  Render and display all the photo file items
$('#photosTab').html($.map(json.photoFiles, renderItem))

Before you get unnecessarily far down the rabbit hole with manual dom interaction, take a look into Facebook's React library.

It allows you to program much more intuitively, and simply by saying that your 'view' is a function of the state of your application at any point in time.

 

 

Hope this helps.

Link to comment
Share on other sites

The example code below returns the values of the photoFiles array:

var json = {"status":1,"recId":"PL-17534","collectionDate":"08-04-2014","collectorsName":"asdf","donorsName":"","sciName":"asdf","family":"asdf","comName":"asdf","variety":"","area":"asdf","photoFiles":["1.jpg","internet.jpg"]};

	
	$.each(json.photoFiles, function(key, val){
		 //return '<img src="'+val+'"><br>';
		 console.log( '<img src="'+val+'"><br>');
		
	});

I'm not sure I fully understand what you are trying to achieve by returning in an anonymous function but that code works to give you access to each of the values.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.