Incorporate a for loop in Javascript to add a variety of items (object1, object2, and object3) to an array

Currently, I am facing a challenge in my project where I need to fetch data from an open-source API. The issue lies in the fact that the API provides objects that must be grouped into an array named ingredients. These objects are labeled as

strIngredients1, strIngredients2, strIngredients3
, and so on. I am looking for a way to achieve this by utilizing a for loop, but I am unsure of how to proceed.

As of now, I have not attempted any solutions because I am uncertain about the approach to take.

EDIT: To clarify further, let's assume there are three objects named obj1, obj2, and obj3. My goal is to add all of them to a single array called arr. Typically, this would involve manually inserting each object into the array:

// Manual method

var arr = []
var obj1 = {}
var obj2 = {}
var obj3 = {}

arr.push(obj1, obj2, obj3)

However, I aim to accomplish this using a for loop instead. Somewhat similar to the following:


// For Loop

for (let i = 1; i <= 20; i++) {
    arr.push('obj'+i)
}

Unfortunately, this approach only adds strings, not the actual objects. What steps should I take next?

Answer №1

It seems like you may need additional information, but based on my understanding, the data retrieved from the fetch call appears in this format:

[
  { items: [item1, item2, ... ,itemN] },
  { items: [item1, item2, ... ,itemN] }
]

You are looking to combine all the items into a single array.

const items = [] // store all items here?

If that is the case, you can try the following approach:

const items = []

for(const obj of objArray){
  items.push(...obj[items])
}

This code snippet spreads all the items from each object into the push function, effectively adding every value to your items array. I hope this solution proves useful! If not, please provide more details for further assistance.

Answer №2

All the necessary variables are contained within 'this'

for (let j = 1; j <= 30; j++) {
    list.push(this['var'+j])
}

Answer №3

You have two options:

Option 1:

const arr = []
const obj1 = { a: 1 }
const obj2 = { b: 2 }
const obj3 = { c: 3 }

// nestedObjects needed - to group objects for pushing

const nestedObjects = [obj1, obj2, obj3]

nestedObjects.forEach(o => arr.push(o))

Option 2:

Utilize global context 'this' in a function

function dd() {
  const arr = []
  this.obj1 = { a: 1 }
  this.obj2 = { b: 2 }
  this.obj3 = { c: 3 }

  for (let i = 1; i <= 20; i++) {
        const value = this[`obj${i}`]
        if (value) arr.push(value)
  }
    
}
dd()

If your variables are in the global context, you cannot access them from within a loop

var arr = []
var obj1 = {}
var obj2 = {}
var obj3 = {}

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

What is the best way to upload an image BUFFER to a website using puppeteer?

What I have learned to do: Save an image file from a source like imgur as a buffer and download it to disk Display an image on a page by uploading it from disk using elementHandle.uploadFile(path) However, this method only works locally on my machine. My ...

Utilizing ReactJS useState to eliminate a className

Basically, I'm trying to remove a className from an element when a button is clicked. I've attempted to use useState hooks and a regular function, with the onClick event on the button triggering this function/setUseState. However, the className l ...

Retrieving data from a stored procedure with XSJS and storing it in a variable

I am currently facing a situation where I need to pass a session user as a parameter to a stored procedure in order to retrieve a receiver value. This receiver value needs to be stored in a variable so that I can use it in another function within an xsjs f ...

JavaScript code to generate diamond-shaped numbers

Greetings everyone! I am facing an issue with my code that is supposed to generate diamond-shaped numbers using javascript. The code involves two javascript functions triggered by a single onclick event, but unfortunately, one of the functions does not see ...

Utilizing Javascript to load a vast amount of data onto the browser, followed by initiating an XML

Looking for a solution to send XML requests containing values and content from files obtained by filling out an HTML form. With 5 large files, some exceeding 70 MB, I have implemented JavaScript functions to load file contents and assemble the XML request. ...

The function getStaticPaths() will generate a 404 error, indicating that the page

I have encountered a persistent issue with the getStaticPaths() function throwing a 404 error. After investigating, I suspect that the problem may lie in the implementation of the getAllPostIds() function, which is supposed to generate an array of object ...

React: Using Chart.js to visualize negative values with a different color in the area

I am implementing a line chart using Chart.js and react-chartjs-2 to display positive and negative values. For positive values, I want the filled area to be green, and for negative values, I want it to be red. Check out the code here import React from &qu ...

Tips for adjusting an svg component to suit various screen sizes

I inserted the following SVG component into my HTML file. It fits perfectly on my tablet, but it's too large for my smartphone. How can we automatically adjust the size of the SVG to fit different screens? <svg viewBox="310 -25 380 450" w ...

React counter variable failing to increment

I have 6 cubes displayed on the screen along with a counter. Whenever a cube is clicked, its background color changes to red and the counter increments by one. However, I'm facing an issue where the counter remains at 1 even after clicking on multiple ...

What might be causing the 500 internal error in jquery.min?

Hello, I am encountering a 500 internal server error when I click this button that performs the following action: $(".btn-email").on('click', function() { swal('Waiting','Please wait, sending email now','info'); ...

"Material-Table does not have the ability to insert a new row

Just started learning JS and React. I'm attempting to integrate Material-table with an add row button, but encountering issues where the added row is not reflecting. Every time I refresh the page, the rows are reset. I suspect there's a problem w ...

The `$refs` variable in Vue can be used to reference a specific Vue component within a class-st

Would it be possible to access this.$refs.label? I am using the package vue-property-decorator. Below is the content of the component: <template> <div> <label ref="label">asd</label> </div> </template> <scr ...

Is there a way to divide a string and insert something into the new array that is created?

I am facing an issue with adding a new fruit to a string that is converted into an array. Here's the scenario: var fruits = "banana,apple"; In an attempt to add a new fruit to this list, I tried converting it to an array and then using the push meth ...

Measuring the height of a div element using Vuejs

Let me explain my current situation: I am trying to determine the height of a DIV component in order to dynamically inform its child component about its size. I have been working on implementing manual loading mode, but I have encountered an issue where t ...

How to work with multiple selections in React material-ui Autocomplete

I'm currently using Material-ui Autocomplete in multiple selection mode. My goal is to retrieve all the selected values when the form is submitted. Although I found a solution on how to get individual values through the onChange event handler from thi ...

Using jQuery to bind the "CTRL+A" key combination to exclusively selecting a specific region

My goal is to modify the CTRL+A shortcut so that instead of selecting all text, it will only select specific content within containers with a class of xyz. Unfortunately, I have not been successful in getting this functionality to work. Even attempting to ...

How can I retrieve the total number of records (count) in an XML response using PostMan?

Hello, I'm currently attempting to determine the length of an XML response but I'm running into some issues. The error message I am encountering is as follows: "There was an error in evaluating the test script: ReferenceError: xml2json is not def ...

Implementing Formik in React for automatic updates to a Material-UI TextField when blurred

Presently, I am developing a dynamic table where users can simultaneously modify multiple user details in bulk (Refer to the Image). The implementation involves utilizing Material-UI's <TextField/> component along with Formik for managing form s ...

Ways to display a default view in React

I am working on a React website that has three different routes. My goal is to have the first route, named Home, automatically displayed when a user lands on the site. Below is the code snippet from my App.js: <Router> <Navigation /> <Sw ...

Updating the state across various components proves to be a challenge when relying on both the context API and higher order components

I have been working on updating the application state using the context API instead of using Redux, as I do not require all of its features and want to avoid prop drilling. With TypeScript, I created a global context and a higher-order component (HOC) wrap ...