How to replace previously added elements in a Javascript array using array.push

As I populate an array with objects, each iteration of the for loop updates the previous items in the array.

I've experimented with different types of loops such as for-each, for, and for-of.

var arrResult = new Array;

for (let element of accessoriesToDisplay) {
    var obj = {};
    var obj = await AdaptiveCardImporter.accessoryCard(element.Name,
     element.Price, element.ProductDescription, element.URL, element.ImgURL);
    arrResult.push(obj);
}

The final array should contain 3 distinct objects rather than just a repetition of the last one. Previously, this code functioned properly until I relocated the accessoryCard method from the main JavaScript file.

Watcher:

https://i.sstatic.net/TR1NW.png

https://i.sstatic.net/1GZgJ.png

https://i.sstatic.net/p38WA.png

Answer №1

Your coding concept seems solid. Your code should run smoothly, but the issue seems to be with your await statement - something appears to be off there. A recreated version of your code demonstrates this:

const getObj = e => new Promise(resolve => setTimeout(() => resolve({val:e}), 300))

async function main() {
  var arrResult = []
  var accessoriesToDisplay = [1, 2, 3]


  for (let element of accessoriesToDisplay) {
    var obj = await getObj(element)
    console.log(obj)
    arrResult.push(obj);
  }
  
  console.log(arrResult)
}

main()

However, it seems that your original code is having issues. Consider using console.log(JSON.stringify(obj)) during each loop iteration to verify if the returned object matches what you expect - sometimes Chrome can automatically update the value.

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

Storing TypeScript functions as object properties within Angular 6

I am working on creating a simplified abstraction using Google charts. I have implemented a chartservice that will act as the abstraction layer, providing options and data-source while handling the rest (data retrieved from a REST API). Below is the exist ...

The path specified as "react-native/scripts/libraries" does not exist in the file

I've been troubleshooting an error on Github - https://github.com/callstack/react-native-fbads/issues/286. After cloning the repository and running it, I discovered that the error persisted. I am currently updating packages to investigate why this rec ...

What is the best way to dynamically access or create nested objects by iterating through a loop based on a given number?

Can someone assist me in refactoring a couple of if-statements that are almost identical, but differ only in hierarchy within the currentHierarchie object? I am looking to consolidate these into a loop or similar construct. The number of if statements shou ...

Submitting a POST request using a Chrome Extension

I am in the process of developing a Chrome extension popup for logging into my server. The popup contains a simple form with fields for username, password, and a submit button. <form> <div class="form-group"> <label for="exampleInputE ...

Converting a Class Component to a Functional Component in React: A Step-by-Step

I need to refactor this class-based component into a functional component class Main extends Components{ constructor(){ super() this.state = { posts:[ { id:"0", description:"abc", imageLink: ...

Executing a Javascript function within a PHP script

I am trying to retrieve JSON data from a JavaScript function and use it as a variable in PHP. Here is the function I have: <script type="text/javascript" src="Scripts/jquery-1.9.1.min.js"></script> <script> $(fu ...

Access Denied - jQuery Print Preview not authorized?

Every time I try to print using the jQuery Print Preview Plugin, an error message appears in Firebug: Error: Permission denied to access property 'name' if (window.frames[i].name == "print-frame") { I'm not sure what this error means ...

Challenges faced with the $_POST["var"] variable in Yii Controller

I am facing an issue with $_POST["var"] in my controller. It appears to be empty. How can I capture the string entered in my textField? View <?php Yii::app()->clientScript->registerCoreScript("jquery"); ?> <script type="tex ...

Manipulating nested lists in Vuejs by removing elements

After reading about how to remove elements from lists in VUEJS on Stack Overflow, I came across various methods like this.$remove, splice, and this.$delete. I was curious about applying these methods to a nested loop structure in my code which goes three l ...

Creating a nested object in React's handleChange method: a step-by-step guide

Hey there, I've been working on an onChange function called handleChange for a set of dynamically created inputs. This function receives the event and then performs the following actions: const handleChange = (e) => { const updatedValues = [...va ...

Creating an object based on its type in JavaScript is a simple task

In a recent project, I found myself using the following code: function foo(type, desc) { var p = new type(desc); } Although I am not a JavaScript expert, it seems to be functioning properly in Chrome. Can anyone confirm if this is valid JavaScript? Th ...

Guide on generating a video thumbnail using JavaScript Application

Searching for a way to easily create a thumbnail from a video for uploading alongside the video itself to a server? I've been looking for JavaScript libraries to simplify the process without much luck. The scenario involves the user selecting a video ...

.NET Bingo: Converting String to Array and Variable Setting

I have a collection of thirty random numbers stored in a single cell in a database, separated by spaces. Currently, I am evaluating and displaying them individually in a row like this: <%# Eval("winning_numbers").ToString().Split(' ')[0]% ...

"Inserting" a fresh key-value pair into a JavaScript Object

I know that with arrays, only array elements can be added using the .push() method. My goal is to achieve a similar functionality for objects. I am familiar with both dot and bracket notation, so this is not a basic question for me. However, I need to do ...

Observing the data retrieved from an AJAX request

Currently, I have this AJAX call in my code: $('#search').keyup(function() { $.ajax({ type: "GET", url: "/main/search/", data: { 'search_text': $('#search').val() }, suc ...

Changing the state using setState outside of the component does not trigger an update

My shop is situated within the store.js file like all the other Zustand stores: const retryStore = create(set => ({ retry_n: 0, setGRetry: (retry_n) => set(state => ({ ...state, retry_n, })), })); export { retryStore }; ...

React page is not loading properly after refreshing, displaying unprocessed data instead

Hello everyone! I am currently working on developing an app using Node, React, and Mongoose without utilizing the CRA command, and I have also incorporated custom webpack setup. Initially, I was able to build everything within a single React page (App.jsx ...

What causes dates to shift by 24 hours?

I am facing an intriguing datetime dilemma. It seems like I just can't crack it and it's driving me crazy. Perhaps I overlooked something or didn't approach it in the right way. Currently, I am retrieving data from Mongo using Axios. The da ...

What are some ways to render a React component when its ID is only determined after making an AJAX call?

Currently, I am working on developing a chat application where a chat message is immediately displayed (using a React component) once the user sends it by hitting the Enter key: https://i.sstatic.net/MJXLd.png https://i.sstatic.net/S6thO.png As shown in ...

Combining JSON arrays

I have two JSON Arrays provided below: Array 1: [ { id : 1, b: 1}, { id : 2, b: 2}, { id : 3, b: 3}, ] Array 2: [ { id : 1, c: 1}, { id : 3, c: 3}, { id : 4, c: 4} ] In my Node.js code, I am looking to merge both arrays as shown ...