Navigating through JSON object

One of my challenges involves working with a JSON object structured like this:

var Obj = {
    'id1': 'abc',
    'id2': 'pqr',
    'id3': 'xyz'
}

In my code, I have an asynchronous method being called within a loop, as shown below:

var otherObj = {};
for (i in Obj) {

    var someData = Obj[i];

    File.upload(someData).then(function(response) {
        otherObj[i] = response.data.url;
    });
}

However, the resulting otherObj looks like this:

otherObj = {
    'id3':'url1',
    'id3':'url2',
    'id3':'url3',
}

This issue prompts me to inquire about the best approach for linking each key from the Obj object with its respective response from File.upload().

Answer №1

To prevent the issue of each callback for File.upload().then seeing the last iterated value of i, you can utilize an Immediately Invoked Function Expression (IIFE).

for (i in Obj) {

    var someData = Obj[i];
    (function(i) {
        File.upload(someData).then(function(response) {
            otherObj[i] = response.data.url;
        });
    })(i);
}

By using this approach, the variable i will be preserved within the execution context of the callback for File.upload().then, ensuring that each callback can access the correct value of i specific to its iteration.

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

Is there a way to turn off _moz_resizing on my browser?

I am currently using the nicEdit editor and have successfully integrated my own custom image resizing script. However, I am facing an issue where the default _moz_resizing feature in Firefox is interfering with my custom script. My goal is to have specifi ...

Refreshing the page results in a 404 error when utilizing React Router

I am currently facing an issue with my web application setup. Back-End My back-end consists of a Node.js/express server that serves files in response to specific requests made to certain routes. Front-End On the front-end, I have React pages that commu ...

Arranging elements based on specific coordinates

const renderTimeSlots = () => { const timeSlots = []; for (let i = parseInt(workStartsAt); i <= parseInt(workEndsAt); i++) { if (i !== 0) { timeSlots.push( <div className="flex flex-row cursor-pointer"> ...

A guide on utilizing pandas to extract data from a jsonlines document

I'm relatively new to Python and attempting to extract data from a file that contains millions of lines. My initial attempt at parsing it using Excel proved to be unsuccessful. How can I efficiently parse this data and export it into an Excel file for ...

Utilizing JavaScript functions within a Twig loop

I need help with a code that displays the phone number of various posters. {% for ad in ads %} ... <a class="btn" onclick="showNumber()" id="showNumber"><span class="fa fa-phone"></span> View Phone Number</a> <input id ...

Adding HTML content inside an iFrame at a specific cursor position in Internet Explorer

Does anyone know a method to insert HTML into an iFrame specifically for IE? I have been using execCommand insertHtml in Chrome and Firefox, but it doesn't seem to work in IE. I was able to paste HTML into a content editable div using pasteHTML, howe ...

What is the purpose of storing the Vue instance in a variable or constant?

As a newcomer to Vue, I've noticed that in many tutorials and documentation sources, the new Vue instance is often stored in a variable like app. I'm curious, what is the benefit of saving the Vue instance in a constant or variable? const app = ...

Creating a text-only fadein/fadeout carousel using JavaScript with a similar functionality to Bootstrap

Is there a way to create a fade-in/fade-out text only carousel similar to the one on the header of this website using just a few lines of CSS and Javascript instead of including the whole Bootstrap framework? I examined the code of the website and it appe ...

Troubleshooting: Inability to Alter CSS of Single Element with jQuery

I am trying to change the grayscale of specific elements when hovering over them individually, instead of changing all elements with the same class at once. I have written the following code for this purpose: tpj(".cftoverlay").hover(function(){ tpj(t ...

Connecting to PostgresSql through Web Services

Currently, I am in the process of developing an iOS application and integrating a PostgreSql database. My goal is to establish web services that can communicate with the database for data retrieval and insertion purposes. For instance, I aim to set up a we ...

Can a constructor function be utilized as a parameter type in another function within TypeScript?

Recently, I came across TypeScript and after watching some video reviews, I see great potential in it. It seems to offer better code completion, implicit code documentation, and enhanced type safety for JavaScript. I'm currently in the process of con ...

Listening for an event triggered by a child Vue component within the same parent

My project is composed of 4 components: Header, Content, Footer, Main. Each of these components are separated into individual .vue files. Here is the code for Main.vue: <template lang="pug"> .maincomponent header content footer </template&g ...

Finding the source of the err.kind expression in the MERN stack: Unraveling the mystery

Recently, I've been delving into the world of MERN stack development and came across an interesting technique for Error Handling in a tutorial. The tutorial showcased various expressions that can be used to identify different types of errors being thr ...

Navigating Dynamically between tabs - A How-to Guide

I am working on a mat-tab Angular app where I need to dynamically generate links and transfer them to a navLinks object. Despite ensuring that the concatenation is correct, it seems like my approach is not working as expected. Here's a glimpse of what ...

Employing the unshift method on a two-dimensional array

I've been experimenting with the unshift function on a multidimensional array, but I'm having trouble getting it to work as expected. Using shift works fine and does what I need, but unshift doesn't behave properly. Here is the array I&apo ...

What is the easiest way to transform this json data into plain text format?

Snippet: if (message.content.startsWith(config.prefix + 'shop')) { const shop = LabyMod.getShop('all').then(shop => shop.map((sh) => sh.name)); const awaitShop = await shop console.log(JSON.stringify(awaitShop)) ...

The error message "Unexpected token < in JSON at position 0" is indicating a SyntaxError in the

I am facing an issue with the API on this specific page. Although the API is working fine on other pages, it seems to be encountering a problem here. I'm not sure what's causing the issue. Below is the code snippet: export async function getStati ...

What is the way to instruct Mongoose to exclude a field from being saved?

Is there a way in Mongoose to instruct it to not save the age field if it's null or undefined? Or is there a method to achieve this in Express? Express router.put('/edit/:id', function(req, res) { Person.findOneAndUpdate({ _id: req.p ...

Utilize a form with a table layout to send all data to an IEnumerable Controller method

I'm experiencing an issue with a form containing data presented in a table structure @model IEnumerable<myType> @Html.AntiForgeryToken() @using (Ajax.BeginForm("Save", "NOC", null, ajaxopts, new { @encType = "multipart/form-data", @id = "myform ...

Creating unique jQuery objects by comparing specific object properties

I am looking to create an array of unique objects by removing duplicate objects with specific property values. For example, consider the following code snippet where event1 and event2 have identical titles and start values, while event3 and event4 share th ...