SharePoint JavaScript CSOM: Best way to deal with Lookup fields?

I'm new to CSOM (I've used SPServices up to this point), and I'm trying to learn the basics to getting list items. I have a list with lots of columns, several of which are lookups to other lists. When I try to get and print out one of the lookup columns, it comes out as [Object object]. I'm guessing that the lookup fields are getting returned as objects that contain the whole entry from the lookup list. Is that correct? If so, what's the best way to get the fields that I want to display from the object? See my code below:

<script src="/_layouts/1033/init.js" type="text/javascript"></script>
<script src="/_layouts/MicrosoftAjax.js" type="text/javascript"></script>
<script src="/_layouts/sp.core.js" type="text/javascript"></script>
<script src="/_layouts/sp.runtime.js" type="text/javascript"></script>
<script src="/_layouts/sp.js" type="text/javascript"></script>
<script type="text/javascript" src="../SiteAssets/js/jquery-1.12.3.min.js"></script>

<SCRIPT type=text/javascript>
$(document).ready(function() {

function GetListItemsFromSPList(listId) {  
    var context = new SP.ClientContext.get_current();
    var web = context.get_web();
    var list = web.get_lists().getById(listId);
    var query = SP.CamlQuery.createAllItemsQuery();
    var allItems = list.getItems(query);
    context.load(allItems, 'Include(Id, ContractType)');
    context.executeQueryAsync(Function.createDelegate(this, function () { onQuerySuccess(allItems); }),
        Function.createDelegate(this, this.onQueryFailed));
}

function onQuerySuccess(allItems) {
    var listItemInfo = '';
    var ListEnumerator = allItems.getEnumerator();
    while (ListEnumerator.moveNext()) {
        var currentItem = ListEnumerator.get_current();
        listItemInfo += '\nID: ' + currentItem.get_id() +
        '\nContractType: ' + currentItem.get_item('ContractType');

    }

    alert(listItemInfo.toString());
}
function onQueryFailed(sender, args) {
    alert('Error: ' + args.get_message() + '\n' + args.get_stackTrace());
}

var listId = "{STRING-OF-LISTID-CHARACTERS}";
GetListItemsFromSPList(listId);

});

</SCRIPT>

The alert prints out: ID: 1 ContractType: [object Object]

Answers:

Answer

The Lookup field stores object (e.g. 5;#someValue) that has two properties

  1. lookup Id (5)
  2. Lookup Value (someValue)

Please try to get lookup value by below mentioned way.

var lookupObject = oListItem.get_item('lookupFieldName');
var lookupValue = lookupObject.get_lookupValue();
var lookupId = lookupObject.get_lookupId();

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.