2

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]

3
  • loop through the array and build your $filter. Finally append it in the query Nov 13, 2015 at 12:23
  • can u pls help me with the syntax for doing that..
    – KumarV
    Nov 13, 2015 at 12:37
  • see my answer @vikash Nov 13, 2015 at 12:52

3 Answers 3

2

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
  • 4
    Looping arrays is 1980s BASIC style coding; Just use 'ID eq '+ids.join(' or ID eq '); Nov 13, 2015 at 13:34
  • forgot to think about join(). You can add it as answer. I will give +1 Nov 13, 2015 at 13:38
1

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 ');
}
1

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 ')}`;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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