none
How to loop through SharePoint list column names using JQuery/JavaScript? RRS feed

  • Question

  • Hi there

    How to loop through SharePoint list column names using JQuery/JavaScript?

    Thanks.

    Friday, March 3, 2017 12:51 AM

All replies

  • Hi,

    Have below code block for your reference. It may help you.

    function getListViewFields(listTitle, viewName) {
        var context = new SP.ClientContext.get_current();
        var web = context.get_web();
        var list = web.get_lists().getByTitle(listTitle);
        var view = list.get_views().getByTitle(viewName);
        var listFields = view.get_viewFields();
        context.load(listFields);
        context.executeQueryAsync(getFieldNames, logError);
    
        function getFieldNames() {
            var e = listFields.getEnumerator();
            while (e.moveNext()) {
                var fieldName = e.get_current();
                console.log(fieldName);
            }
        }
    
        function logError(sender, args) {
            console.log(args.get_message());
        }
    }

    Thanks.

    Friday, March 3, 2017 6:31 AM
  • Try below Simple REST API Code...It will retrieve all the columns...

     $.ajax({
    
         url: _spPageContextInfo.webAbsoluteUrl+"/_api/web/lists/getbytitle('<list Name>')/fields",
         type: "GET",
         headers: {
             "accept": "application/json;odata=verbose"
         },
         success: function(data, request) {
    
               $.each(data.d.results, function(key, val) {
    
                 console.log('Title' + val.Title);
             });
    
    
         },
         error: function(err) {
             console.log(JSON.stringify(err));
         }
    
     });


    Friday, March 3, 2017 6:49 AM
  • Hi,

    I am assuming you are working on SharePoint 2013.

    If you are trying to get all the list columns once you get the list items response using REST API there is simple JavaScript method to get columns as below

    var columns = Object.keys(listItem);

    You can do this for first item.

    If you are trying to get the fields there is a REST call as follows

    <<site url>>/_api/web/Lists/getByTitle('<<List Title>>')/Fields

    You can loop through response get internal names of each field.

    Please provide me the additional details if neither of the above ones you are looking.

    All the Best,

    Venkat Konjeti

    --------------------------------------------------------------------------------------------------------------

    Please vote if this answer helpful

     
    Friday, March 3, 2017 2:12 PM