Loop through each item in an array

Currently, I am leveraging vue.js and lodash to iterate through a list of events in order to extract the promoted events. My goal is to then store each event in a new object or array that holds a refined list of promoted events. However, instead of consolidating all objects into a single array, I am ending up with separate arrays for each object.

       getPromotedEvents() {
            // Retrieve a list of promoted events
             _.forEach(this.events, (eventList) => {
                if(eventList.promote_event){
                    let arr = [];
                    arr.push(eventList)
                    console.log(arr);
                }
            });
        },


This results in [{}], [{}], [{}] being returned, as opposed to [{},{},{}].

Answer №1

One reason for the issue could be that the array is being reset inside the loop. To resolve this, you can try the following approach:

fetchPromotedItems() {
  let items = [];
  //retrieve a list of promoted items
  _.forEach(this.items, (item) => {
    if (item.promote_item) {
      items.push(item)
      console.log(items);
    }
  });
},

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

How can I apply Ben Alman's debounce jQuery function in my code?

I am currently utilizing a project found at https://github.com/cowboy/jquery-throttle-debounce My code seems to be somewhat functional, however the debounce feature is not functioning as expected. This results in the waterfall function being triggered for ...

Encountered a snag with submitting data via AJAX: received an error message stating

I created this custom script for a contact form on my website, and it seems to be working fine. However, I'm encountering an issue where instead of storing the data in my database, all I get is [object HTMLCollection]. Can someone please explain wh ...

Exploring the capability of the Videoshow NPM module in conjunction with

I've been working on using videoshow to convert a series of images into a video. I've made several changes to my code, but it seems like it's pretty much the same as what's described in the module's documentation. However, I keep e ...

Do commas at the end of JSON objects pose a risk of breaking

After diving into the proposed JavaScript features, one that caught my attention is the idea of supporting trailing commas in object literals and arrays. When it comes to parameters, trailing commas are not relevant, so let's put that aside for now. ...

Highlighting table rows when hovering in IE with JQuery - compatibility across all versions

I have a table on my jsp page with multiple rows and columns. I want to ensure that visitors can easily follow along when they interact with the table - by highlighting the row or column they hover over with a different background color. Although the **hov ...

A JavaScript function written without the use of curly braces

What makes a function good is how it is declared: export declare class SOMETHING implements OnDestroy { sayHello() { // some code to say hello } } However, while exploring the node_modules (specifically in angular material), I stumbled up ...

I'm a beginner in React Native and I'm attempting to display a "Hello World" text when the button is pressed. Unfortunately, the code below is not

''' import { StyleSheet, Text, View, SafeAreaView, TouchableOpacity, Button } from 'react-native' import React from 'react' const handlePress = () => { <View> <Text> Greetings universe ...

"Navigate back to a previous page in Vue Router without having to

I am currently exploring the option of creating a back button in my Vue.js application using vue-router that mimics the behavior of the browser's native back button. The challenge I'm facing is that when using history mode for the router and tryi ...

Get a single object from an array with .single method provided by @ngrx

Seeking to retrieve an Observable containing a single object from an array of objects in my store. I aim to utilize the .single operator, which should throw an exception if there is not exactly 1 object present. However, I'm struggling with this as my ...

Imagine a scenario where your json_encode function returns API data that is already in JSON format. What would

It has been a while since I last worked with JSON/PHP/AJAX, and now I am struggling to access the returned data. The AJAX function calls a PHP script that makes an API call returning JSON in $data. The JSON is then decoded using $newJSON = json_decode($da ...

Is it possible to include an if/else statement within a tailwind class in React components?

I want to dynamically change the background color of a div based on a condition. If the condition is true, I want the background color to be white; otherwise, I want it to be black. Despite trying to achieve this using an if/else statement, the background ...

merge two structures to create a unified entity

I have been searching in vain, can you please advise me on how to combine these two simple forms into one? I want it to be like a box with a select option and a button. The challenge for me is merging the two different actions, ".asp", into one script fo ...

Incorporating an element into a nested array

I have an array stored in a variable called 'items' with various products and their attributes. I am looking to randomly generate a popularity score between 1 and 100 for the items that currently do not have one. This is my current array: const ...

Tips for successfully executing queries with Axios within a Vue application

Is there a way to send query parameters using Axios so that I can access them in my backend code using req.query.email? The following approach doesn't seem to be working as expected: this.$http.post(this.$BASE_URL + 'agents/auth/create-password&a ...

Tips for populating an array with information gathered from an axios request within a React application

Currently, I am using axios to fetch data from an API and attempting to store the retrieved data in a variable that represents an array within the state of the component. However, when I try to do so, I encounter the following error: Objects are not valid ...

Execute angular.js as a callback function, such as within a $.ajax call

In developing my app, I am primarily working with two key JavaScript files: resources_loader.js and app.js. The role of resources_loader.js is to load some JSON files that are utilized by app.js. However, the issue arises when considering the sequence in ...

Json node tabbing

[ { "idn" : "liquido", "categoria": "Aromatizante Ambiental Liquido", "productos": [ { "nombre": "Canela" }, { "nombre": "Chanel" }, { "nombre": "Citrus" }, ...

Commitments and incorporating items from an array into objects nested within a separate array

My current project involves a command line node application that scrapes valuable data from a specific website and stores it in a CSV file. For the scraping functionality, I am utilizing scrape-it, which enables me to successfully extract all the necessa ...

Functionalities of HTML controls

I currently have a select element in my HTML code which looks like this: <select> <option id="US" value="US"> </option> <option id="Canada" value="Canada"> </option> </select> My requirements are twofold: ...

Display the results of the constantly changing JSON response

I am expecting to receive a dynamic JSON response based on the provided input. Here is an example: { results: [ { email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="087c6d7b7c487c6d7b7c266b6765">[email protec ...