Sparlarva
Sparlarva

Reputation: 804

Turn a for loop on an object into a .map

I have been told my function:

 for (const key of Object.keys(temp)) {
 this.sessionData.push(temp[key]);
 }

Must now use a .map instead,

I have tried this below:

Object.keys(temp).map(function(key) {
  this.sessionData[key];
})

But 1 I don't know if it's actually accurate, and also, it cant access the data outside of the scope of the function it is in, here is the whole function below:

public sessionData;

sessionDates(sessionsData) {
  const temp = {};
  this.sessionData = [];
  sessionsData.forEach(session => {
    const date = moment(session.startDatetime).format('DDMMYYYY');
    if (temp[date]) {
      temp[date].push(session);
    } else {
      temp[date] = [session];
    }
  });

Object.keys(temp).map(function(key) {
  this.sessionData[key];
})

TRYING TO USE THIS BELOW... session data is undefined, it can't access out of the scope?

    Object.keys(temp).map(function(key) {
  this.sessionData[key];
})

But this works..

 for (const key of Object.keys(temp)) {
 this.sessionData.push(temp[key]);
 }

So this new .map method can't access anything out of its scope.. sigh!

If anybody can help that would be amazing! Thanks!

Upvotes: 0

Views: 72

Answers (1)

Duncan Thacker
Duncan Thacker

Reputation: 5188

In Javascript all functions can access variables from outside (called "higher scope") - it's one of the strengths of the language and is called "capture".

The reason your code is failing is because it's using this.sessionData inside a function declaration, which cases problems because this in javascript is... somewhat complex. But you don't need it!

You also need to make sure you return the value you want to output. Here's how I would write it:

 this.sessionData = Object.keys(temp).map(key => temp[key]);

Upvotes: 2

Related Questions