速记的方式来构建具有可变属性名JS对象 [英] Shorthand way to construct JS object with variable property name

查看:96
本文介绍了速记的方式来构建具有可变属性名JS对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有创建一个属性字段变量对象的速记方式?

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

说我有变量 PROP.Todo.PRIORITY ='优先',然后使用的骨干在这个例子中,我想保存这个属性,我怎么能避免创建新的对象,将其分配给一些变量,然后设置属性?

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆