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.
Use the JavaScript function JSON.parse() to convert text into a JavaScript object: const obj = JSON.parse('{"name":"John", "age":30, "city":"New York"}');
JavaScript provides two methods, i.e., Object. assign() and push() to append values to an object. The Object. assign() method appending values to objects by key/value pairs.
One way is to add a property using the dot notation: obj. foo = 1; We added the foo property to the obj object above with value 1.
Using an Object Literal This is the easiest way to create a JavaScript Object. Using an object literal, you both define and create an object in one statement. An object literal is a list of name:value pairs (like age:50) inside curly braces {}.
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
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With