使用key:value在一行中创建对象

时间:2014-08-24 19:34:06

标签: javascript object

如果可能的话,我需要在一行中实现:

我有一个对象

var object1 = {};

object1['key_1'] = "value_1";
object1['key_2'] = "value_2";
object1['key_3'] = "value_3";

我需要从对象传递一个函数(不仅是值),键 - 仅字符串值

for (var key in object1)
    FunctionTemp({key:object1[key]}); // - this don't work as I need, and eval() method I don't want

也许有类似的东西

FunctionTemp((new {})[key]=object1[key]) - its don't work!!! :)

2 个答案:

答案 0 :(得分:0)

没有功能,你所要求的是不可能的。

你想要做的是:

var key = getKey(); //some means of determining a key dynamically
var val = getVal(); //some means of determining a value dynamically
var obj = {};
obj[key] = val;
this.doSomething(obj);

您需要的是基于动态键/值组装对象的another method

this.doSomething(_.object([[getKey(), getVal()]]));

答案 1 :(得分:0)

因为你真的想要它在一行中你可以这样做:

var temp;
for (var key in object1)
    FunctionTemp(((temp = {}) && (temp[key] = object1[key]))? temp: null);

但我认为它不再具有可读性,最理想的解决方案是将其分解为几行。

var temp;
for (var key in object1) {
    temp = {};
    temp[key] = object1[key];
    FunctionTemp(temp);
}