Home > front end >  How to store objects created in a loop inside array defined outside of loop in Javascript
How to store objects created in a loop inside array defined outside of loop in Javascript

Time:03-05

I have the following for loop in which this_block gets created and then filled in:

for (i = learning_trial_idx.length - 1; i >= 0; i--) {

  target = Math.floor(Math.random())

  these_trials = learning_trial_idx.filter(x => x.from != target)

  this_block = [];

  for (let i = 0; i < these_trials.length; i  ) {
      this_block.push(these_trials[i])
  }

  this_block = this_block.filter(function (a) {
    var key = a.to   '|'   a.from;
    if (!this[key]) {
        this[key] = true;
        return true;
      }
    }, Object.create(null));
}

How can I go about storing this_block each time into something like const all_blocks = {}, which is defined outside of the for loop?

CodePudding user response:

You can do that by declaring first const allBlocks = { thisBlock: [] } and push-ing inside thisBlock inside the for loop: allBlocks.thisBlock.push(theseTrials[i])

  • Related