Saving a value to a variable before adding it to an array, rather than inserting it directly into the array

Currently I am making an API call, and processing the response data as follows.

      request.get('https://example.com', function(error, response, body) {
        body = JSON.parse(body);
        name = body.name
        image = body.picture.data.url
        userList[i].name = name;
        userList[i].image = image;
        console.log(userList[i])
      }

After implementing this code block, it appears to be functioning well as the variables are visible in the array. However, when I attempt the following approach:

      request.get('https://example.com', function(error, response, body) {
        body = JSON.parse(body);
        userList[i].name = body.name;
        userList[i].image = body.picture.data.url;
        console.log(userList[i])
      }

And then try to print out the userList array, the name and image properties seem to be blank or not stored properly.

I am curious to understand why the information is not being stored correctly within the array?

Answer №1

Regardless of whether you use variables or not, your code should function correctly. Refer to the following example:

var data = {title:'Title', content : {data: {url:'example.com'}}}
var count = 0;
var dataList = [];
dataList[count] = {};
dataList[count].title = body.title;
dataList[count].link = body.content.data.url;
console.log(dataList);
console.log(dataList[count]);

Answer №2

Experiment with adding an item to an array

fetch('https://example.com')
    .then(response => response.json())
    .then(data => {
        let newItem = {};
        let itemList = [];
        newItem.name = data.name;
        newItem.image = data.picture.data.url;
        itemList.push(newItem);
        console.log(itemList[itemList.length - 1]);
    });

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

Creating identical HTML output using PHP and JavaScript

Often when working with PHP, I find myself creating helper functions that generate complex HTML. For example, ensuring the accessibility and error-handling capabilities of form elements can be a challenging task, so I will have a PHP function to handle thi ...

An associative array in PHP with just a single item

One of the functions in my code returns an array containing results from the database. $resultArray = $db->Select($sql); I then loop through each result in the array and remove those that do not meet a certain requirement. foreach($indexToRemove as $ ...

Saving a collection of CustomObjects in UserDefaults

My custom class is defined as Set<ListItem>, and I am trying to store it in userDefaults. However, I am encountering an error that says Attempt to set a non-property-list object as an NSUserDefaults when I attempt to do so. I have tried changing it t ...

Is there a way to delay the inner for loop and have the outer for loop wait until the inner loop has completed its iteration?

Is there a way to achieve this with delays? How can I coordinate the outer loop to wait for the inner loop to finish, and ensure that each iteration of the inner loop is delayed by 2 seconds? The desired outcome looks like this: The outer loop will print ...

Issue encountered when utilizing pass by reference in stack implementation (C language)

In my attempt to implement a stack using arrays, I have encountered an issue. #include<stdio.h> #include<stdlib.h> #define MAX 5 typedef struct { int arr[MAX]; int top; }STACK; //#typedef struct stack STACK; //------------- ...

What is the best way to display an arrow specifically for the selected item in JQuery?

Check out this example I've been working on: https://jsfiddle.net/6yg8ckno/ HTML Preview: <div class="patrat1 inline"> <p class="menu1"><img class="sageata" src="http://paul.dac-proiect.ro/wp-content/themes/wpbootstrap/images/log ...

Using Ruby variable as a parameter in JavaScript

Is there a way to include a ruby variable as a parameter in a JavaScript function for a Rails checkbox? Here is an example of what I'm trying to do: <%= check_box_tag 'Sugestão', prato.id , prato.sugestao,:class => prato.categoria_pr ...

Link several jQuery elements to a function simultaneously

Having 3 jQuery objects is my current situation: var first = $('.el1'); var second = $('.el2'); var third = $('.el3'); I am trying to attach a "change" event to all of them simultaneously, but facing some challenges :( $(fi ...

What is the best way to retrieve the updated value after using React useState in a function?

Take a look at this snippet of React code: const [win, setWin] => useState(false) const [guessedNumber, setGuessedNumber] => useState(undefined) const clickHandler = () => { setGuessedNumber(randomNumber()) if(guessedNumber === 10) { ...

Organizing your web application directories with AngularJS and Node.js

As I dive into the world of learning node.js and angularjs, I find myself struggling with how to best organize and structure my folders and their contents. Despite coming across some existing questions on this topic, none have provided a solution that trul ...

Best Practices for Laravel and Vue Collaboration

Currently, I am in the process of developing a straightforward invoice system using Laravel. In order to facilitate editing, I need to create a view that consists of a table where rows can be dynamically added and removed. I initially considered using jQu ...

Comparison between storing data locally and using AngularJS $cacheFactory

I'm facing a challenge with storing large amounts of client-side data and I'm unsure of the best approach to take. Currently, I am utilizing AngularJS's cacheFactory which is effective, but all the data gets reloaded with each new session. W ...

Jquery mouseenter fails to detect when leaving span element and does not trigger again

If I have a code snippet like this <div id='one'>xyz <span id='two'>abc</span> </div> I am attempting to hover over element one, then element two, and finally back to one. However, I am facing an issue with j ...

Struggling with loading react storybook

I am having trouble getting my storybook app to start. It is stuck in a loading state with no errors showing in the console. Can anyone help me figure out what I am doing wrong? Check out the screenshot here storybook/main.js const path = require(' ...

What is the best way to link a newly created contact to the current user in Mongoose?

I'm faced with the challenge of creating a contact that is specifically added to the current user's contact array. Currently, my controller only creates a generic contact and doesn't cater to the individual user. Controller: function cont ...

Utilize ASP MVC Controller to handle form submissions containing identical HTML input names with distinct values

Could you assist with cloning an input type in HTML? Here is a sample of the code: <input type="text" id="person" name="Person" class="person-list" /> <input type="text" id="person" name="Person" class="person-list" /> I am trying to retrieve ...

What steps are involved in implementing a search method using a hashtable in Java?

import java.util.Enumeration; import java.util.Hashtable; //@author fsociety public class HashFoo { public static void main(String[] args) { HashFoo <String,String> student = new HashFoo <String,String>(); student.put("1", "A");//L ...

`Is it possible to programmatically click a button using the ref attribute?`

Is it possible to invoke a click event based on the ref attribute using jQuery, in addition to being able to do so based on class and id attributes? The code below is based on ref="btFirst", but I am unsure how to access the ref. JSFiddle link <butto ...

Tips for loading various content types in Fancybox 3

I am utilizing Fancybox 3 for my gallery where I have disabled the opening/closing animation. Here is how I load my gallery: $(document).on('click', '[data-fancybox-var]', function(e) { e.preventDefault(); var links = $(' ...

Tips on utilizing React and Node to upload text as a file to Google Drive

Are you wondering how to incorporate React.js as the frontend and Node.js as the backend for uploading/reading files from Google Drive? In my attempts, I've tried writing a string as a text file and then uploading it to Google Drive by following this ...