Quitch
Quitch

Reputation: 89

Converting array entries into an object with a variable number of parameters

I currently have a bit of code that is as follows:

      $.when(aiFileGen, foeFileGen, foe2FileGen, playerFileGen).then(function (
        aiFiles,
        foeFiles,
        foe2Files,
        playerFiles
      ) {
        var files = _.assign({}, aiFiles, foeFiles, foe2Files, playerFiles);
        self.files(files);
        done.resolve();
      });

A snapshot self.files() is as follows:

Object {/pa/ai/unit_maps/ai_unit_map.json.ai: Object, /pa/units/sea/hover_ship/hover_ship.json.ai: Object, /pa/units/sea/fabrication_barge/fabrication_barge.json.ai: Object, /pa/units/sea/drone_carrier/drone/drone.json.ai: Object, /pa/units/sea/drone_carrier/carrier/carrier.json.ai: Object…}

The problem with this method is that it assumes a set number of parameters, but the number of parameters can change. Therefore I have tried to convert to something more dynamic.

      var filesToProcess = [aiFileGen, playerFileGen];

      filesToProcess.push(foeFileGen, foe2FileGen);

      $.when.apply($, filesToProcess).always(function () {
        self.files(_.assign({}, arguments));
        done.resolve();
      });

However, the output of self.files() is as follows:

Object {0: Object, 1: Object, 2: Object, 3: Object}

Where have I gone wrong in my conversion of method 1 to method 2?

Upvotes: 0

Views: 42

Answers (1)

3limin4t0r
3limin4t0r

Reputation: 21130

The problem is that you always call _.assign({}, arguments) with 2 arguments. Instead you want to pass each argument in arguments as separate argument to _.assign.

This can be done similar to how you've also changed the $.when call. However you'll have to convert the arguments to an array first so you can add the additional {} argument.

var assignArgs = Array.prototype.push.apply([{}], arguments);
self.files(_.assign.apply(_, assignArgs);

However I'd recommend taking a look at the spread and rest syntax (...). This makes passing and accepting a variable amount of parameters a lot easier.

$.when.apply($, filesToProcess).always(function () {
  var assignArgs = Array.prototype.push.apply([{}], arguments);
  self.files(_.assign.apply(_, assignArgs);
  done.resolve();
});

// can be changed to

$.when(...filesToProcess).always(function () {
  self.files(_.assign({}, ...arguments));
  done.resolve();
});

Upvotes: 1

Related Questions