Ryan
Ryan

Reputation: 400

JQuery map filtering?

I've copied and pasted a list.js file off of the internet. It's obtaining a list of files. However, I want to filter the files, so that the only files returned are those with the name index.html. I'm not familiar with Javascript nor jQuery, but I realize the change probably needs to occur within the first 1-9 lines. Any help would be awesome!

function getInfoFromS3Data(xml) {    
  var files = $.map(xml.find('Contents'), function(item) {    
    item = $(item);    
    return {    
      Key: item.find('Key').text(),    
      LastModified: item.find('LastModified').text(),    
      Size: bytesToHumanReadable(item.find('Size').text()),    
      Type: 'file'    
    }    
  });

  var directories = $.map(xml.find('CommonPrefixes'), function(item) {    
    item = $(item);    
    return {    
      Key: item.find('Prefix').text(),    
      LastModified: '',    
      Size: '0',    
      Type: 'directory'    
    }    
  });

  if ($(xml.find('IsTruncated')[0]).text() == 'true') {    
    var nextMarker = $(xml.find('NextMarker')[0]).text();    
  } else {    
    var nextMarker = null;    
  }

  return {    
    files: files,    
    directories: directories,    
    prefix: $(xml.find('Prefix')[0]).text(),    
    nextMarker: encodeURIComponent(nextMarker)    
  }    
}

Upvotes: 2

Views: 1110

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

To achieve this you need to check the name of the file (presumably the Key in your example) matches what you require and return the object, or null if not so that the file is skipped. Try this:

var files = $.map(xml.find('Contents'), function(item) {    
  var item = $(item);   

  if (item.find('Key').text().toLowerCase() !== 'index.html')
    return null;

  return {    
    Key: item.find('Key').text(),    
    LastModified: item.find('LastModified').text(),    
    Size: bytesToHumanReadable(item.find('Size').text()),    
    Type: 'file'    
  }    
});

Upvotes: 1

Related Questions