Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate javascript object name by appending string to object

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.

like image 629
SharpCoder Avatar asked Jun 24 '15 08:06

SharpCoder


People also ask

How do you turn a string into an object in JavaScript?

Use the JavaScript function JSON.parse() to convert text into a JavaScript object: const obj = JSON.parse('{"name":"John", "age":30, "city":"New York"}');

Can you append to an object JavaScript?

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.

How do you append property to an object?

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.

What is {} object in JavaScript?

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 {}.


2 Answers

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

like image 139
Rory McCrossan Avatar answered Sep 28 '22 06:09

Rory McCrossan


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);
like image 45
cosbor11 Avatar answered Sep 28 '22 06:09

cosbor11