How to retrieve a variable from inside a foreach loop in Vue.js

How can I access the value of `this.names` from within a foreach loop?

This is what my code looks like:

<template><div><li>{{ names }}</li></div></template>
var initData = {
  names: '',
  }
}
export default {
  data: function () {
    return initData
  },
  props: ['nameData'],
  methods: {
    printNames: function () {
      let tempData = JSON.parse(JSON.stringify(this.nameData))
      tempData.biglist.forEach(function (nObj) {
        let cName = nObj.CeName
        console.log(cName) // gives long list of names
        this.names = cName
      })
    }
  },

I would like to populate my list with the `names` value. Thank you in advance for your help :)

Answer №1

If you need to access this inside another function scope, such as forEach(), there are two methods you can use.

One option is to simply create a new variable that references your scope:

printNames: function () {
  let scope = this
  let tempData = JSON.parse(JSON.stringify(this.nameData))
  tempData.biglist.forEach(function (nObj) {

    // You can access the scope here

    let cName = nObj.CeName
    console.log(cName) // gives long list of names    
    this.names = cName
  })
}

This way, you will have access to the variable scope inside the forEach loop.

Alternatively, you can utilize arrow functions, which do not create a new scope. This means you will have the same this as outside the forEach loop. Here is an example:

http://jsfiddle.net/2eAqE/1149/

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

Having trouble showing the information in JavaScript

Here is some code snippet: if(data.error) { msg1.textContent=data.error } else { msg1.textContent=data.location msg2.textContent=data.forecast console.log(data.forecast) } }) Unfortunately, I'm facing an is ...

Issue with Vue plugin syntax causing component not to load

I'm facing an issue with a Vue plugin that I have. The code for the plugin is as follows: import _Vue from "vue"; import particles from "./Particles.vue"; const VueParticles = (Vue: typeof _Vue, options: unknown) => { _Vue. ...

federatedSignIn enhancement results in accessToken issuance without scopes

I'm currently facing some challenges while attempting to utilize amplify in my Vue application. When I manually authenticate using Auth.signIn, everything runs smoothly. I receive the access token, pass it to my backend, and successfully retrieve the ...

Retrieve data by sorting based on the count column in a joined table with Sequelize

I've been struggling to make this work for some time and was hoping for some guidance. OBJECTIVE: I'm attempting to sort the posts by the number of likes they currently have. CURRENT: const posts = await db.post.findAll({ include: [ db.user ...

Communicating information across Vue.js components

I am currently working on developing a CRUD web application using Laravel and Vue.js for the first time. My application is connected to a MySQL database, and I have utilized multiple Vue.js components, each of which accesses a specific table in the databas ...

Tips for adding CSS attributes to a <style> tag in Internet Explorer

My current issue involves an ajax web application that loads all parts on a single page, specifically index.html. The inner parts being loaded in index.html have exceeded 32 pages (html, js, css). Now I am facing difficulties with the CSS files that need ...

Adjustable <a> component

There is this element: <a id="lnkViewEventDetails" class="psevdo calendar-event event" style="height: 126px;" href="/someurl/895?responseType=5" onclick="event.stopPropagation();"> I am trying to make it resizable using JQuery UI: $("#lnkViewEvent ...

Is it possible to create a form inside a tooltip?

Looking to incorporate a jQuery feature into a form where a simple yes or no question appears upon hovering over it. However, encountering issues getting jQuery to recognize the dynamically created tooltip and submit alert function not working ("$('#w ...

Make a copy of an array and modify the original in a different way

Apologies for my poor English, I will do my best to be clear. :) I am working with a 3-dimensional array which is basically an array of 2-dimensional arrays. My task is to take one of these 2-dimensional arrays and rotate it 90° counterclockwise. Here is ...

Functionality in Three.js that involves selecting nearby objects with an event handler and ensuring that the self object is

I have spent countless hours today diving deep into the documentation, tutorials, and stackoverflow questions in pursuit of a solution to this issue. I am pleading for your assistance – please take pity on me and help! The problem at hand involves a wat ...

VueJs: Passing the value of a 'computed function' from a child component to its parent component using $emit with an optional payload and $on

As a newcomer to VueJs, I find myself unsure about how to pass an optional payload. Can someone guide me on passing the value returned by a computed function from a child component to a parent component using this payload? I aim to create a standalone sea ...

Retrieve specific elements from an array based on the other elements present in the array

I am working with a result set that consists of various combinations from the following data structure: [ ["1st", "FELONY"], ["2nd", "FELONY"], ["3rd", "FELONY"], ["1st", "MISDEMEANOR"], ["2nd", "MISDEMEANOR"], ["3rd", "MISDEMEANOR"]] For example, it co ...

Utilize a Vue2 component that has been defined in the same file within another

I'm attempting to establish a reference from one locally defined vue2 Component to another in the following manner: new Vue({ el: '#app', components: { 'foo': {template: '<p>Foo</p>'}, 'bar&ap ...

Assign the form's data to a backbone model in order to invoke a REST service

I am a newcomer to backbone. I have set up a form. <form name="searchForm" method="POST" id="CandidateSearch" ` enctype="application/json" accept-charset="utf-8"> <br> <br> <div class="container" style="backgro ...

Drag-and-drop functionality in Angular JavaScript Tree View for rearranging nodes and inserting new nodes

Exploring the world of JavaScript Tree Views and Angular as a beginner. After scouring the internet for information, I'm struggling to find a solution to my specific query. Looking for a tree-view component that seamlessly integrates with Angular, c ...

printing jquery value inside html elements

I have a jQuery code snippet that is currently displaying an alert popup when triggered. However, I would like to print the result in the HTML body instead. I attempted the following but it did not work: // Do What You Want With Result .......... :) $(" ...

Why does JQuery ajax always fail to succeed? Where could the error be?

I am attempting to create an ajax call to a php server that utilizes Wordpress. I have set up a rewrite rule to handle the redirection of ajax calls: function Ajax_rules_setup(){ add_rewrite_rule( 'ajax/([^/]*)', ...

Adjust the size of an array based on the specified index

I have an array defined as... let myArray = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] ...along with a starting index let start = 2 and an ending index let end = 5. I want to resize the array by taking elements from start to end, for example: start ...

Utilizing multiple local images effectively within a Next.js 13 component: Best practices for implementation

Currently working on a Next.js project and utilizing the Image component to showcase images. Familiar with importing a single local image like so: import Image from 'next/image'; import profilePic from '../public/me.png'; export defaul ...

Submit function causes mutation in React form state

My current project involves learning React on my own and creating a small single-page React app using an Axios API. I'm facing a persistent issue with a POST request that keeps failing. After extensively using console.log, it appears that the form inp ...