Getting and setting multiple items from a Sharepoint list using CAML query?
-
08-02-2021 - |
Pergunta
I have a SharePoint list Catalog
.
Using camlQuery
I can get a list item value called Price
.
With the following code I get the Price
value of the list element which has the ID
5 and store it in a variable price_id5
.
var itemprices = {};
// Gets values from Catalogue list; but they can't be used in the Position list because of different formats
function retrieveListItems() {
var clientContext = new SP.ClientContext.get_current();
catalogueList = clientContext.get_web().get_lists().getByTitle('Catalog');
var camlQuery = new SP.CamlQuery(); // initiate the query object
camlQuery.set_viewXml('<View><Query><Where><In><FieldRef Name=\'ID\'/><Values><Value Type=\'Number\'>5</Value><Value Type=\'Number\'>6</Value><Value Type=\'Number\'>7</Value></Values></In></Where></Query></View>');
itemColl = catalogueList.getItems(camlQuery);
// returns the item collection based on the query
context.load(itemColl);
context.executeQueryAsync(retrieveListItemsSuccess, retrieveListItemsFail);
}
function retrieveListItemsSuccess() {
var listItemEnumerator = itemColl.getEnumerator();
while (listItemEnumerator.moveNext()) {
var oListItem = listItemEnumerator.get_current();
itemprices[oListItem.id] = oListItem.get_item('Preis');
console.log("itemprices 5: " + itemprices[5]);
console.log("Price of list item at is:" + itemprices[oListItem.id]);
}
}
// This function is executed if the above call fails
function retrieveListItemsFail(sender, args) {
alert('Failed to get list items. Error:' + args.get_message());
}
How can I efficiently get the Price
value of other list elements and store them in variables like price_id6
, price_id7
etc.?
I want to store them in variables in order to set these values in another list, but I don't know how without writing the three functions for every single price..
Solução
This is really more of a general JavaScript question than SharePoint-specific, but the easiest way is just to use an array variable: var itemprices = [];
and then push the values as you find them itemprices.push(oListItem.get_item('Price'));
, and then you can loop through your array when you want to do something with each Price.
Alternatively, you could use a Javascript object, using the IDs as the Key,
so var itemprices = {};
, then save each value like itemprices[currentId] = oListItem.get_item('Price');
However, looking at your code though, if you have multiple IDs, you put them all in a single caml using the <In>
element, for example:
<View><Query><Where><In><FieldRef Name=\'ID\'/><Values><Value Type=\'Number\'>5</Value><Value Type=\'Number\'>6</Value><Value Type=\'Number\'>7</Value></Values></In></Where></Query></View>
and then that way, in your retrieveListItemsSuccess
function, your listItemEnumerator.moveNext()
will actually loop through all 3 items (or however many ID's are in your query).