用可变属性名构造JS对象的简写方式 [英] Shorthand way to construct JS object with variable property name
问题描述
是否有一种快捷方式来创建具有属性字段变量的对象?
Is there a shorthand way to create an object with a property field variable?
假设我有变量 PROP.Todo.PRIORITY = 'priority'
然后使用 Backbone 在这个例子中,我想保存这个属性,我怎样才能避免创建一个新的对象,将其分配给某个变量,然后设置属性?
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?
我想实现这一目标:
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.
推荐答案
如果你只是想要更简单的方法来创建对象,使用辅助函数怎么样?
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.
这篇关于用可变属性名构造JS对象的简写方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!