Using Foreach to reference data as "this"

I am attempting to iterate through this information in order to assign a value to each.

const keys = Object.keys(response.data)
keys.forEach((index, element) => {
    // let query = "this."+element
    this[element] = response.data[element]
});

The desired output is as follows:

this.name = response.data.name
this.password= response.data.password

...

Answer №1

Your code has a few issues that need to be addressed, none of which are related to accessing this.

Firstly, the arguments in your callback function are in the wrong order. The element should come first, followed by the index. This might be confusing if you're used to jQuery, as it uses the opposite order in its .each() and .map() methods.

Secondly, you're not utilizing the element correctly. Using .element will access a property named "element" literally, rather than using the value stored in the variable element. To access a property dynamically, you should use [element]; check out this link for more information: Dynamically access object property using variable

const key = Object.keys(response.data)
key.forEach((element) => {
    this[element] = response.data[element]
});
class MyClass {
  copyProps(response) {
    const key = Object.keys(response.data)
    key.forEach((element) => {
      this[element] = response.data[element]
    });
  }
}

obj = new MyClass;
obj.copyProps({
  data: {
    name: "MyName",
    age: 10
  }
});
console.log(obj);

Alternatively, you could use Object.assign() to copy properties:

Object.assign(this, response.data);

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

Translate3d increases the whitespace towards the end of the page

After implementing a smooth scroll on my webpage using transform translate3d, I encountered an issue. The translate3d function seems to be adding extra space at the end of the document, as illustrated here: https://codepen.io/anon/pen/WEpLGE I suspect the ...

Modifying the values of Highcharts-Vue chart options does not result in any changes once they have been

I recently started incorporating Highcharts into my Vue project using the highcharts-vue library. A) Initially, in pure JavaScript, the following code snippet functions as expected: let b = 5; let data = { a: b } console.log('data', data.a) ...

Tips for refreshing an element after modifying a data-* attribute

I have an element that has the following CSS style: #element:after { content: attr(data-percent); } In an attempt to change the data-percent attribute using jQuery, I used this code: $('#element').data('percent', '50%'); ...

The functionality of smooth scrolling is not compatible with the overflow-y property

Looking to implement a smooth scroll feature, I came across an example online and tried to adapt it. Here's the code I'm working with: https://jsfiddle.net/4DcNH/144/ I've added specific conditions to the html and body elements (changing t ...

What is the best way to add a blob to the document object model (

I am a beginner when it comes to working with blobs, and I am looking for some guidance to avoid wasting hours on unsuccessful brute-force attempts. I have been using the PHP code below (sourced from here) to retrieve the base64-encoded image from my data ...

Did I incorrectly associate the function with the button causing it to always be executed?

I am working on a PHP page, where I have some initial content followed by session initialization code: <?php session_start(); ?> The requirement is to display a disconnect button only if the user is logged in, indicated by the presence of $_SESS ...

Release date approaching, but not as anticipated

Utilizing Java servlet to construct a portion of HTML and sending it with a JsonPrimitive for display in a dialog box. Here is the code snippet: ja = new JsonPrimitive( "<a href='#' onclick='return showDueDateUpdateDialogue(" + invoice. ...

Using Express.js to leverage Vega for generating backend plots

Exploring ways to create plots using backend code and transfer them to the front end for display. Could it be feasible to generate plots on the server-side and then transmit them to the front end? I am interested in implementing something similar to this: ...

Identifying and retrieving elements in JavaScript

I'm trying to extract the unique selector path of an HTML element using a script I found at this source. The generated path appears as follows: html>body>section:eq(3)>ul>li:eq(1)>div Can someone guide me on how to use JavaScript or j ...

Angular - What is the best way to simulate an HTTP request in testing?

Although I currently have a basic code that triggers an actual HTTP request : @Component({ selector: 'my-app', template: ` <div> <h2>Hello {{person?.id}}</h2> </div> `, }) export class App { name:str ...

What is the most effective way to incorporate the Gmail compose window concept into Single Page Applications?

I am currently working on a project that would benefit from a user-friendly way to add transactions quickly. I am intrigued by the idea of creating something similar to the Gmail compose pop-up feature on a single page. I am unsure of how to go abo ...

What is the optimal approach for managing multiple languages using React Router version 5?

I am exploring the possibility of incorporating multiple languages into my website using React and React Router v5. Can you provide guidance on the most effective approach to achieve this? Below is a snippet of the current routing code I am working with: ...

When testing units, the scope method in an AngularJS directive fails to execute

I am facing an issue with my Mocha test: 'use strict'; /////////////////////////////////// describe('all admin page directives', function () { let scope, $compile, element, tmp; beforeEach(module('app')); beforeEach( ...

"Encountering an error in Vue3 CompositionAPI: 'quizz is not defined' while trying to call a function from the

When attempting to call a function, I am encountering an error that says "Uncaught ReferenceError: quizz is not defined." <script setup> import { defineProps } from "vue"; import { useRouter } from "vue-router"; const router = us ...

The npm request was unsuccessful due to a self-signed certificate within the certificate chain causing the failure

I am attempting to launch a React Native project using Expo from this site npm install expo -g expo init AwesomeProject npm start However, when running npm start, I encounter the following error: npm ERR! code SELF_SIGNED_CERT_IN_CHAIN npm ERR! er ...

Displaying a Jquery slider by clicking on links

I am interested in setting up a slider for two different forms. Specifically, I plan to have one form labeled Form 1 and another labeled Form 2 displayed as text. When users click on Form 1, a table containing the form will slide out from underneath the ...

What is the best way to update HTML element contents with new code without losing any associated JavaScript functions?

I am attempting to replace the content within $('#product_blocks') with new HTML while also maintaining the jQuery event listeners on a similar element ID. var newHtml= '<div id="clickme">hello this text will be replaced on click</ ...

JavaScript: Populating an Array with Image URLs Using a Loop

My image gallery project has hit a roadblock and my JavaScript skills are not up to par. Maybe it's time to brush up on the basics with a good book from the library. Here's what I want to achieve: 1. Create an array of URL's for each imag ...

Class for making elements draggable using jQuery UI

Is it possible to use jQueryui's draggable/droppable combo and add a class to the dragged item when dropped into a specific container, rather than adding a class to the container itself? I've tried adding a class to the container, but that is not ...

Is there a way to implement field validation in a Vue wizard form?

Trying to implement form validation using Joi in a Vue wizard form, but not sure how to set it up correctly. The objective is to control the fields before progressing to the next and final page using the next() method. I want to keep the simplicity of th ...