Shorthand way to construct JS object with variable

2020-03-24 07:02发布

问题:

Is there a shorthand way to create an object with a property field variable?

Say I have the variable PROP.Todo.PRIORITY = 'priority' and then, using Backbone in this example, I want to save this property, how can I avoid having to create a new object, assigning it to some variable and then set the property?

I want to achieve this:

var tmpObj = {};
tmpObj[PROP.Todo.PRIORITY] = "high";
this.model.save(tmpObj);

I've tried something like this, which was unsuccessful:

this.model.save(({}[PROP.Todo.PRIORITY] = "high"));

Any suggestions? I'm going to be writing a lot of long-hand object declarations otherwise.

回答1:

If you just want an easier way to create the object, how about using a helper function?

function obj(prop, value) {
  var o = {};
  o[prop] = value;
  return o;
}

this.model.save(obj(PROP.Todo.PRIORITY, "high"));

I'm not sure I understand the latter part of your question:

I'm going to be creating a lot of temporary objects otherwise.

You'll have to create an object in any case, and I doubt creating objects is a performance issue.



回答2:

If you save only one parameter, Model.save has a an alternative way of receiving arguments, (key,value,options)

http://backbonejs.org/#Model-save

save model.save([attributes], [options])
[...] As with set, you may pass individual keys and values instead of a hash. [...]

which means you could write your example as

this.model.save(PROP.Todo.PRIORITY, "high");

If you want to save multiple properties simultaneously, you will have to write a temporary object.