How can I loop through a json result by substituting column names for a variable

End result: I'm building a table from a list (~25 columns). I want to attach custom classes to each cell based on the cell's value during the loop to parse json data.

I made a REST call for list items in one function, and am looping through the results in another.

  1. I'm using the for loop for(i=0; i<data.d.results.length; i++)
  2. I'm building the table within the loop

$displayTable = $displayTable + $cellClass + $eventClass + data.d.results[i].columnName_1 + $cellClose;

$displayTable = $displayTable + $cellClass + $eventClass + data.d.results[i].columnName_2 + $cellClose;

  1. I want to attach an additional class to all instances based on their values using an if, statement.

  2. Is there a way to loop through the json result by substituting column names for a variable? It'll make it easier both to write comparison statements with each value on the list and make it easier to display (loop) all columns without writing out 25 column names.

An example will be using a $cellInstance variable variable instead of a column/field name as seen in point 2 above. This would be able to

``$displayTable = $displayTable + $cellClass + $eventClass + data.d.results[i].$cellInstance + $cellClose;`


I can think of a couple of Options:

1: Get all fields in item from rest and filter out SharePoint Default fields.

2: create a new Content type which contains all desired fields.

_api/web/lists/getbytitle('Samples')/contenttypes('"+ contentType +"')/fields

first one gets all Content types. Note there are trash one in the one you want to filter out of the results with ?filter=

Second one gets all field in the specific contenttype

And please use the following in your for loop:

var length = data.d.results.length;
for(var i = 0; i < length; i++) {
// your code

Why this is better:

1: lets say you have 100 items your Loop is checking if data.d.results.length is a valid int.

2: i = 0; makes a global variable. If you have this asyn this or something else that runs asyn and reuse 1 you can get confusing results. Also changing global variables is slower.

Hope this helps.

If you have questions, I won't be able to respond before monday.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.