I have array with id's of list items so I want those items from list using rest.

I found this

/_api/web/lists/getByTitle(listTitle)/items?$filter=(ID eq 1) or (ID
 eq 2) or (ID eq 3)

So in this I need to use array values instead of hard coded values.

How would I do it if i have an array as array[j]

  • loop through the array and build your $filter. Finally append it in the query – Atish Dipongkor Nov 13 '15 at 12:23
  • can u pls help me with the syntax for doing that.. – KumarV Nov 13 '15 at 12:37
  • see my answer @vikash – Atish Dipongkor Nov 13 '15 at 12:52
up vote 1 down vote accepted

Write some javascript to build your $filter and then append it to the query url.

function getFilter(ids) {
    var idFilter = "ID eq ";
    var filter = "";
    for (var i = 0; i < ids.length; i++) {
        if (i == ids.length - 1) {
            filter += idFilter + ids[i];
        } else {
            filter += idFilter + ids[i] + " or ";
        }
    }
    return filter;
}

Now assume that name of id's array is ids:

var ids = [1, 2, 3];

Now call the above function

var filterById = getFilter(ids);

Output: "ID eq 1 or ID eq 2 or ID eq 3"

Now change the query url like

"/_api/web/lists/getByTitle(listTitle)/items?$filter='"+ filterById +"'";

Check this jsbin how getFilter() works.

  • 2
    Looping arrays is 1980s BASIC style coding; Just use 'ID eq '+ids.join(' or ID eq '); – Danny '365CSI' Engelman Nov 13 '15 at 13:34
  • forgot to think about join(). You can add it as answer. I will give +1 – Atish Dipongkor Nov 13 '15 at 13:38

Adding this from the comments because I found it very useful and almost missed it:

var filterById = 'ID eq ' + ids.join(' or ID eq ');
var url = "/_api/web/lists/getByTitle(listTitle)/items?$filter='"+ filterById;

You can make it even more generic like this:

function contains(prop, values) {
    return prop + ' eq ' + values.join(' or ' + prop + ' eq ');
}

Building on the two previous answers, I feel it's a bit easier to read it this way:

var ids = [1, 2, 3];
var filters = ids.map(function(id){
    return 'ID eq ' + id;
}
var url = "/_api/web/lists/getByTitle(listTitle)/items?$filter=" + filters.join(' or ');

or in ES6:

var ids = [1, 2, 3];
var filters = ids.map(id => `ID eq ${id}`);
var url = `/_api/web/lists/getByTitle(listTitle)/items?$filter=${filters.join(' or ')}`;
New contributor
gschwendt is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.

Your Answer

 
discard

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.