5

I am getting a Javascript object req.files . This object can have multiple files under it. req.files is an object and not an array.

So of if user adds three files, the object will look like:

req.files.file0
req.files.file1
req.files.file2

where file0, file1 etc is another object.

User can add upto 15 files. How can I check loop over such objects & read information from req.files.fileX ? I need to support IE 11 & chrome.

1
  • 1
    req.files["file" + i] Commented Jun 24, 2015 at 8:07

2 Answers 2

6

You can use bracket notation to access the properties of an object by a string. Try this:

for (var i = 0; i < Object.keys(req.files).length; i++) {
    var file = req.files['file' + i];
    if (file) {
        // use file here...
    }
}

Example fiddle

Sign up to request clarification or add additional context in comments.

Comments

1

So I'm assuming your req object looks like this:

var req = {
  files: {
    file0: {},
    file1: {},
    file2: {},
    //...
    file14: {}
  }
};

If so, you can reference the file like this: req.files['file0']

So your loop could look like this:

for (prop in req.files) {
    var file = req.files[prop];
}

But you don't even need to use a loop:

var getReqFile = function(x){
  return req.files['file' + x] || null;
}
var file = getReqFile(5);

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.