Unable to retrieve key value pairs of objects

Currently, I am utilizing FormData in my VueJS FrontEnd to send images to my Express Server for storage in a Mongo DB using gridfs-stream and mongoose. Despite the image objects successfully reaching the server, I am struggling to access their key-value pairs.

Upon executing the following code:

let part = req.files
for (const prop in part) {
   console.log('part.${prop} = ${part[prop]}')
}

The output I received was:

part.files[0] = [object Object]
part.files[1] = [object Object]

However, when attempting to access part.files[0], I encountered the following error:

TypeError: Cannot read property '0' of undefined

Below is the structure of the Object:

{ 'files[0]':
 { data: <Buffer ff d8 ff e0 00 10 4a 46 49 46 00 01 01 01 00 48 00 48 00 00 ff db 00 43 00 08 06 06 07 06 05 08 07 07 07 09 09 08 0a 0c 14 0d 0c 0b 0b 0c 19 12 13 0f ... >,
 name: 'e0ZnCwP.jpg',
 encoding: '7bit',
 mimetype: 'image/jpeg',
 truncated: false,
 size: 259454 },
'files[1]':
 { data: <Buffer ff d8 ff e0 00 10 4a 46 49 46 00 01 01 00 00 48 00 48 00 00 ff c0 00 11 08 06 40 04 c8 03 01 22 00 02 11 01 03 11 01 ff c4 00 1f 00 00 01 05 01 01 01 ... >,
 name: 'Me.jpeg',
 encoding: '7bit',
 mimetype: 'image/jpeg',
 truncated: false,
 size: 108021 } }

Thank you in advance for any assistance!

Answer №1

object.files[0] retrieves the first element of the property named files, assuming it is an array. However, in your object, there are string keys like files[0], files[1], and so on. This seems like an error. If it's intentional, you can access these properties indirectly as object["files[0]"], object["files[1]"], object["files[" + index + "]"], and so forth.

Answer №2

There are two types of JSON data structures: #1

var part = {
files : { 
    { 
        data: <Buffer ff d8 ff e0 00 10 4a 46 49 46 00 01 01 01 00 48 00 48 00 00 ff db 00 43 00 08 06 06 07 06 05 08 07 07 07 09 09 08 0a 0c 14 0d 0c 0b 0b 0c 19 12 13 0f ... >,
         name: 'e0ZnCwP.jpg',
         encoding: '7bit',
         mimetype: 'image/jpeg',
         truncated: false,
         size: 259454 
    }, { 
        data: <Buffer ff d8 ff e0 00 10 4a 46 49 46 00 01 01 00 00 48 00 48 00 00 ff c0 00 11 08 06 40 04 c8 03 01 22 00 02 11 01 03 11 01 ff c4 00 1f 00 00 01 05 01 01 01 ... >,
         name: 'Me.jpeg',
         encoding: '7bit',
         mimetype: 'image/jpeg',
         truncated: false,
         size: 108021 
    } 
}

Or the one you received: #2

var part = { 
    'files[0]': { 
    data: <Buffer ff d8 ff e0 00 10 4a 46 49 46 00 01 01 01 00 48 00 48 00 00 ff db 00 43 00 08 06 06 07 06 05 08 07 07 07 09 09 08 0a 0c 14 0d 0c 0b 0b 0c 19 12 13 0f ... >,
     name: 'e0ZnCwP.jpg',
     encoding: '7bit',
     mimetype: 'image/jpeg',
     truncated: false,
     size: 259454 
}, 
'files[1]': { 
    data: <Buffer ff d8 ff e0 00 10 4a 46 49 46 00 01 01 00 00 48 00 48 00 00 ff c0 00 11 08 06 40 04 c8 03 01 22 00 02 11 01 03 11 01 ff c4 00 1f 00 00 01 05 01 01 01 ... >,
     name: 'Me.jpeg',
     encoding: '7bit',
     mimetype: 'image/jpeg',
     truncated: false,
     size: 108021 
} 

The distinction between them lies in #1 where the files variable is an array, so you access them like this: part.files[i]. However, in #2 (your case) you have array key/value pairs, so you access your file by part['files['+i+']'].

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Setting a variable in Angular after a successful AJAX call

Working on a new small application and experimenting with Angular. Encountering an issue where I am making an AJAX GET request upon clicking a button. After receiving the response, I want to set a variable to hold the result, but for some reason the variab ...

Looping through ng-repeats, extracting checked checkbox values in Angular

I am currently dealing with multiple nested ng-repeats in my project, and the third level down consists of a group of checkboxes. Initially, I receive an array of options for these checkboxes, which I handle with the following code snippet: <div class= ...

Generate a dynamic HTML table using an array of objects

I have a dataset that I need to transform into an HTML table like the one shown in this image: https://i.sstatic.net/gRxJz.png Despite my attempts to write the code below, it seems that the rows are being appended in different positions. Is there another ...

Completed Animation with Callback in AngularJS CSS

Currently working with AngularJS and hoping to receive a notification upon completion of an animation. I am aware that this can be achieved with javascript animations such as myApp.animation(...), but I'm intrigued if there is an alternative method wi ...

What is the best way to iterate through an Object.entry and multiply one value by another key value within a loop?

I am looking to enhance the functionality of my Vue.js composition API web application by calculating the total number of employed workers in different sectors. However, I want to multiply the number of workers by another key:value property instead of ju ...

Issue found (in promise): Invalid Syntax detected at script.js line 8, character 42

I am in the process of developing a tool that retrieves ROBLOX asset IDs using this particular API. I am utilizing the product info function through an API GET request. Despite being near completion, I keep encountering the error Uncaught (in promise) Synt ...

Conflict in Vue.js between using the v-html directive and a function

Below is the component template for a notification: <template> <div> <li class="g-line-height-1_2"> <router-link :to="linkFromNotification(item)" @click.native="readNotification(item)" v-html="item. ...

A step-by-step guide on retrieving a value from a DateTime picker in a React application

I am utilizing Material-UI to create a DateTime picker. You can check out my demo code here. In order to observe the current selected value, I have added console.log to the function handleChange. However, I am facing an issue where the value does not chan ...

How to Utilize the Vue Instance With the 'this'

Trying to implement this in my VueJs methods results in an error message: this is undefined It seems like arrow functions may not be suitable as their this does not bind to the expected context. Switching to a regular function still causes the same err ...

Using JavaScript variables in a Jinja array

I encountered a frustrating issue that has been causing me some trouble. In my project setup, data is being transferred from Python to the frontend using Jinja in the form of a 2D list. My goal is to loop through this array using a for loop, but I'm ...

Implementing specifications throughout the entire nodejs route

In my Nodejs app, I have a RESTful API where I need to check for a user's role before sending a response with data or 404 error. apiRouter.route('/users') .get(function (req, res) { var currentUser = req.decoded; if(curr ...

Disabling the submit button after submitting the form results in the page failing to load

I am encountering an issue with my HTML form that submits to another page via POST. After the form validates, I attempt to disable or hide the submit button to prevent double submission and inform the user that the next page may take some time to load. He ...

Can a valid HTML structure be reconstructed from a fragment?

Imagine you have just <td>text<td></tr>. Clearly, by itself, it is not considered valid HTML (and neither is just <td>...</td>). Is there a simple method to reconstruct a valid HTML structure from this fragment? It should lo ...

Having trouble getting the finally clause to work properly in Angular JS version 1.7

In my current project, I am utilizing Angular JS 1.7. Recently, I encountered an issue while using the finally clause within a promise: $http.put( url, null, { headers: { 'Content-Type': 'application/json' } } ).then( ...

Performing AJAX requests to dynamically update multiple DIVs

Encountering difficulties with adding additional input fields to a page, each of which contains jquery code for appending more select boxes related to them. The base html setup is as follows: <p id="add_field"> … </p> <div class="show_sub ...

Sort through an array using various prefixes and suffixes as filtering conditions

I have come across various questions and answers related to this particular issue, but most of them involve using the includes or indexOf methods. The problem at hand is how to filter an array (names in this scenario) using two different arrays - one with ...

Error: Unable to access the value property of a null object (React/JS/TS)

I created a function that dynamically determines the background color based on a specific value. const backgroundColorResolver = () => { allQuestions.map((aq) => { if (aq.averageAnswerValue <= 4) return "#EE7362"; if (a ...

The request to retrieve data from the model at http://localhost:9000/model/data.json resulted in a 404

This is the path to my directory I have a npm server running on http://localhost:9000/ to utilize the cytoscape module. However, my server is unable to locate my json file. What could be the issue with my code? This is the source code of my index.js file ...

Tips for preserving the integrity of square brackets while extracting data from JSON

Everyone: We've decided to utilize Newtonsoft JSON.NET for serializing some C# POCOs, and here's what we have: { "RouteID": "123321213312", "DriverName": "JohnDoe", "Shift": "Night", "ItineraryCoordinates": [ [ 9393, 44 ...

What are the steps to configure ESlint and Prettier with the Airbnb style guide for a React Native/JavaScript project (Expo) in VS Code?

I have looked through numerous tutorials on this topic, but I haven't been able to get it to work. In the tutorials, when you run npm install eslint, it usually prompts you in the command line about using a popular style guide. However, this no longer ...