0

I have a function that loops over an array of objects and builds an object depending on some parameters. It should return the build object which represents a state object of a component that I will set. However, I would like to use the Array.foreach but I have no idea how to call the function after the foreach loop is done.

The function looks something like this:

 buildStateObject= (someArray: Array) => {
    let stateobject= {};
    someArray.foreach(item => {
      switch (item.Someparameter) {
        case 1:
          stateobject.someProp1= item.message;
          break;
        case 2:
          stateobject.someProp2= item.message;
          break;
        // code omitted
      }

    });
     return stateobject;
  };

and in my component I have something like this which obviously does not work :

if(someJson.jsonArray)
    this.setState(this.buildStateObject(someJson));

So what I am looking for is something like this:


Promise.all(buildStateObject).
  then((theResultObjectMaybe)=>{this.setState(theResultObjectMaybe);})

I tried to figure this out but I was not able to. I am also not sure if this is a good practice todo.

[Edit]

@PaulJanicki thank you for pointing the error out. There were just type errors. However one error you pointed out was also in my code which results in a Unhandled promise rejection and I assumed this was because the forEach was async and the result was not yet processed.

The problem was a type error foreach instead of the correct forEach

zlZimon
  • 2,334
  • 4
  • 21
  • 51
  • You are returning the `stateobject` in the `forEach` (also - camelcase), but you'd have to return it after the loop is finished, so the `buildStateObject`-function actually returns something – Thomas Altmann Oct 15 '19 at 11:14
  • I think this might be helpful to you. https://stackoverflow.com/questions/13343340/calling-an-asynchronous-function-within-a-for-loop-in-javascript/50291886#50291886 – Gyan Oct 15 '19 at 11:16
  • @ThomasAltmann you are right, I fixed the issue – zlZimon Oct 15 '19 at 12:52

1 Answers1

1

You are missing the return statement outside of the forEach method, in the buildStateObject function. Also forEach should be camelCase.

 function buildStateObject(someArray) {
  let stateobject = {};
  someArray.forEach(item => {
    switch (item.someparameter) {
      case 1:
        stateobject.someProp= item.message;
        break;
      case 2:
        stateobject.someProp= item.message;
        break;
      // code omitted
    }
  });
  
  return stateobject;
}

function setState(state) {
  console.log(state);
}

var someJson = [{
  message: 'first',
  someparameter: 1
}, {
  message: 'second',
  someparameter: 2
}]

setState(buildStateObject(someJson))

Also consider that stateobject.someProp will be overwritten with each loop execution, not sure if that's the intended behaviour.

Pawel Janicki
  • 425
  • 3
  • 8