Search code examples
javascriptarrayssharepointsharepoint-2010

How to create a javascript array from a SharePoint List?


I'd like to convert a sharepoint list into an array where each dictionary in the array has all key values from a given sharepoint record.

I've tried the following:

function array_from_sharepoint_list(){
    var array = []
    var context = SP.ClientContext.get_current()
    var list = context.get_web().get_lists().getByTitle('Sharepoint_List')
    var caml = new SP.CamlQuery()
    caml.set_viewXML('')
    var listitems = list.getItems(caml)
    context.load(listitems,'Include(ID,Title,col_one,col_two)')
    context.executeQueryAsync(
        Function.createDelegate(this,function(){
            var listEnumerator = listitems.getEnumerator();
            while (listEnumerator.moveNext()){
                var list_item = listEnumerator.get_current();
                var item_dictionary = {ID:list_item.get_item('ID'),Title:list_item.get_item('Title'),col_one:list_item.get_item('col_one'),col_two:list_item.get_item('col_two')}
                array.push(item_dictionary)
            }
        },
        Function.createDelegate(this,function(){})))
    return array 
}

The result does not give me the array needed with every column from the sharepoint list, since it only pulls four columns and I do not know all the column names.


Solution

  • I prefer using REST API, with jQuery:

    function array_from_sharepoint_list(ListName){
        var array = []
        var appWebUrl = _spPageContextInfo.webAbsoluteUrl;
    
        $.ajax({
            url: appWebUrl + "/_api/web/lists/getbyTitle('" + ListName + "')/items",
            type: "GET",
            async: false,
            headers: {
                "accept": "application/json;odata=verbose"
            },
            success: function (data) {
                array = data.d.results;
            },
            error: function (err) {
                console.log(err);
            }
        });
        return array 
    }
    

    REST API documentation: https://msdn.microsoft.com/en-us/library/office/jj860569.aspx