2

I have some code that shows me all the items (files and folders) in a document library, but everything appears on the same level. How can I see which items sit in which folders?

Currently the output looks something like this:

folder 1 -> folder
folder 2 -> folder
folder 3 -> folder
item 1-1 -> item
item 1-2 -> item
item 2-1 -> item
item 3-1 -> item
item 3-2 -> item

Where item 1-1 and 1-2 are in folder 1, item 2-1 in folder 2 and item 3-1 and 3-2 in folder 3.

function FindItems() {
    var ctx = SP.ClientContext.get_current();
    var web = ctx.get_site().get_rootWeb();

    var cqy = new SP.CamlQuery();
    cqy.set_viewXml("<View Scope='RecursiveAll'><ViewFields><FieldRef Name='ID' /><FieldRef Name='Title' /></ViewFields><RowLimit>1000</RowLimit></View>");     

    var items = web.get_lists().getByTitle('Site Pages').getItems(cqy);

    ctx.load(items, 'Include(Title,FileSystemObjectType,DisplayName,FileLeafRef)');

    ctx.executeQueryAsync( 
        function () {
            var itemEnum = items.getEnumerator();

            while (itemEnum.moveNext()) {
                var item = itemEnum.get_current();

                var itemTitle = item.get_item('FileLeafRef');
                var itemType  = ( item.get_fileSystemObjectType() == 1 ? 'folder' : 'item' );
                console.log( itemTitle + ' -> ' + itemType );
            }
        },
        function(sender,args){
            console.log('Error: ' + jQuery.param(args));
        }
    );
}
3

Find folder name from ServerUrl of your document. It should look like

"/{LibraName}/{FolderName}/{fileName.extention}"

So the folder is always before the document.

Coding Changes

cqy.set_viewXml("<View Scope='RecursiveAll'>
                 <ViewFields>
                   <FieldRef Name='ID'/>
                   <FieldRef Name='Title' /> 
                   <FieldRef Name='ServerUrl' />
                </ViewFields>
           <RowLimit>1000</RowLimit></View>");

ctx.load(items, 'Include(Title,FileSystemObjectType,DisplayName,FileLeafRef, ServerUrl)');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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