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

天大地大妈咪最大 提交于 2019-12-13 06:41:25

问题


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]


回答1:


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();


来源:https://stackoverflow.com/questions/42009997/sharepoint-javascript-csom-best-way-to-deal-with-lookup-fields

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!