[Solved] How to use Foreach data as “this” [closed]


You have several problems with your code, neither of which has to do with accessing this.

First, you have ths arguments in the wrong order in the callback. The first argument is the element, the second is the index (maybe you’re used to jQuery — it uses the opposite order in its .each() and .map() methods).

Second, you’re not using the element properly. .element means to access the property literally named element, it doesn’t use the value of the variable element. You have to use [element] to access a property dynamically; see 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);

You could also use Object.assign() to copy properties:

Object.assign(this, response.data);

1

solved How to use Foreach data as “this” [closed]