I'm pulling items out of the DOM with jQuery and want to set a property on an object using the id
of the DOM element.
我使用jQuery将项目从DOM中取出,并希望使用DOM元素的id在对象上设置属性。
Example
const obj = {}
jQuery(itemsFromDom).each(function() {
const element = jQuery(this)
const name = element.attr('id')
const value = element.attr('value')
// Here is the problem
obj.name = value
})
If itemsFromDom
includes an element with an id
of "myId", I want obj
to have a property named "myId". The above gives me name
.
如果itemsFromDom包含一个id为“myId”的元素,我希望obj具有一个名为“myId”的属性。以上就是我的名字。
How do I name a property of an object using a variable using JavaScript?
如何使用JavaScript使用变量来命名对象的属性?
10 个解决方案
#1
407
You can use this equivalent syntax:
您可以使用这种等效的语法:
obj[name] = value
#2
71
With ECMAScript 2015 you can do it directly in object declaration using bracket notation:
使用ECMAScript 2015,您可以直接在对象声明中使用括号符号:
var obj = {
[key]: value
}
Where key
can be any sort of expression (e.g. a variable) returning a value:
其中键可以是任何类型的表达式(如变量),返回一个值:
var obj = {
['hello']: 'World',
[x + 2]: 42,
[someObject.getId()]: someVar
}
#3
11
You can even make List of objects like this
你甚至可以列出像这样的对象
var feeTypeList = [];
$('#feeTypeTable > tbody > tr').each(function (i, el) {
var feeType = {};
var $ID = $(this).find("input[id^=txtFeeType]").attr('id');
feeType["feeTypeID"] = $('#ddlTerm').val();
feeType["feeTypeName"] = $('#ddlProgram').val();
feeType["feeTypeDescription"] = $('#ddlBatch').val();
feeTypeList.push(feeType);
});
#4
2
With lodash, you can create new object like this _.set:
使用lodash,您可以创建这样的新对象_.set:
obj = _.set({}, key, val);
Or you can set to existing object like this:
或者你可以将现有对象设置为:
var existingObj = { a: 1 };
_.set(existingObj, 'a', 5); // existingObj will be: { a: 5 }
You should take care if you want to use dot (".") in your path, because lodash can set hierarchy, for example:
如果您想在路径中使用点("."),您应该小心,因为lodash可以设置层次结构,例如:
_.set({}, "a.b.c", "d"); // { "a": { "b": { "c": "d" } } }
#5
2
First we need to define key as variable and then we need to assign as key as object., for example
首先我们需要将key定义为变量,然后我们需要将key定义为object。例如,
var data = {key:'dynamic_key',value:'dynamic_value'}
var key = data.key;
var obj = { [key]: data.value}
console.log(obj)
#6
1
With the advent of ES2015 Object.assign and computed property names the OP's code boils down to:
随着ES2015目标的到来。OP的代码归结为:
var obj = Object.assign.apply({}, $(itemsFromDom).map((i, el) => ({[el.id]: el.value})));
#7
1
objectname.newProperty = value;
objectname。newProperty =价值;
#8
1
There are two different notations to access object properties
有两种不同的符号来访问对象属性
- Dot notation: myObj.prop1
- 点符号:myObj.prop1
- Bracket notation: myObj["prop1"]
- 括号:myObj(“prop1”)
Dot notation is fast and easy but you must use the actual property name explicitly. No substitution, variables, etc.
点表示法快速简单,但必须显式地使用实际的属性名。没有替换,变量等。
Bracket notation is open ended. It uses a string but you can produce the string using any legal js code. You may specify the string as literal (though in this case dot notation would read easier) or use a variable or calculate in some way.
括号表示法是开放的。它使用一个字符串,但是您可以使用任何合法的js代码生成字符串。您可以将字符串指定为文字(虽然在这种情况下点符号更容易阅读),或者使用变量或以某种方式计算。
So, these all set the myObj property named prop1 to the value Hello:
这些都将myObj属性prop1设为值Hello:
// quick easy-on-the-eye dot notation
myObj.prop1 = "Hello";
// brackets+literal
myObj["prop1"] = "Hello";
// using a variable
var x = "prop1";
myObj[x] = "Hello";
// calculate the accessor string in some weird way
var numList = [0,1,2];
myObj[ "prop" + numList[1] ] = "Hello";
Pitfalls:
陷阱:
myObj.[xxxx] = "Hello"; // wrong: mixed notations, syntax fail
myObj[prop1] = "Hello"; // wrong: this expects a variable called prop1
tl;dnr: If you want to compute or reference the key you must use bracket notation. If you are using the key explicitly, then use dot notation for simple clear code.
如果你想计算或引用这个键,你必须使用方括号表示法。如果您显式地使用键,那么对简单的清除代码使用点符号。
Note: there are some other good and correct answers but I personally found them a bit brief coming from a low familiarity with JS on-the-fly quirkiness. This might be useful to some people.
注意:还有一些好的和正确的答案,但我个人觉得它们有点简短,因为我不太熟悉JS上飞的古怪。这可能对某些人有用。
#9
0
If you want to add fields to an object dynamically, simplest way to do it is as follows:
如果要动态地向对象添加字段,最简单的方法是:
var params= [
{key: "k1", value=1},
{key: "k2", value=2},
{key: "k3", value=3}];
for(i=0; i< params.len; i++) {
data[params[i].key] = params[i].value
}
This will create data object which has following fields:
这将创建具有以下字段的数据对象:
{k1:1, k2:2, k3:3}
#10
0
Based on the wOxxOm's answer, this is an example of use:
根据wOxxOm的答案,这是一个使用的例子:
const data = [
{"id": "z1", "val":10},
{"id": "z2", "val":20},
{"id": "z3", "val":30}
];
const obj = Object.assign.apply({}, data.map((el, i) => ({[el.id]: el.val})));
console.log(obj);
#1
407
You can use this equivalent syntax:
您可以使用这种等效的语法:
obj[name] = value
#2
71
With ECMAScript 2015 you can do it directly in object declaration using bracket notation:
使用ECMAScript 2015,您可以直接在对象声明中使用括号符号:
var obj = {
[key]: value
}
Where key
can be any sort of expression (e.g. a variable) returning a value:
其中键可以是任何类型的表达式(如变量),返回一个值:
var obj = {
['hello']: 'World',
[x + 2]: 42,
[someObject.getId()]: someVar
}
#3
11
You can even make List of objects like this
你甚至可以列出像这样的对象
var feeTypeList = [];
$('#feeTypeTable > tbody > tr').each(function (i, el) {
var feeType = {};
var $ID = $(this).find("input[id^=txtFeeType]").attr('id');
feeType["feeTypeID"] = $('#ddlTerm').val();
feeType["feeTypeName"] = $('#ddlProgram').val();
feeType["feeTypeDescription"] = $('#ddlBatch').val();
feeTypeList.push(feeType);
});
#4
2
With lodash, you can create new object like this _.set:
使用lodash,您可以创建这样的新对象_.set:
obj = _.set({}, key, val);
Or you can set to existing object like this:
或者你可以将现有对象设置为:
var existingObj = { a: 1 };
_.set(existingObj, 'a', 5); // existingObj will be: { a: 5 }
You should take care if you want to use dot (".") in your path, because lodash can set hierarchy, for example:
如果您想在路径中使用点("."),您应该小心,因为lodash可以设置层次结构,例如:
_.set({}, "a.b.c", "d"); // { "a": { "b": { "c": "d" } } }
#5
2
First we need to define key as variable and then we need to assign as key as object., for example
首先我们需要将key定义为变量,然后我们需要将key定义为object。例如,
var data = {key:'dynamic_key',value:'dynamic_value'}
var key = data.key;
var obj = { [key]: data.value}
console.log(obj)
#6
1
With the advent of ES2015 Object.assign and computed property names the OP's code boils down to:
随着ES2015目标的到来。OP的代码归结为:
var obj = Object.assign.apply({}, $(itemsFromDom).map((i, el) => ({[el.id]: el.value})));
#7
1
objectname.newProperty = value;
objectname。newProperty =价值;
#8
1
There are two different notations to access object properties
有两种不同的符号来访问对象属性
- Dot notation: myObj.prop1
- 点符号:myObj.prop1
- Bracket notation: myObj["prop1"]
- 括号:myObj(“prop1”)
Dot notation is fast and easy but you must use the actual property name explicitly. No substitution, variables, etc.
点表示法快速简单,但必须显式地使用实际的属性名。没有替换,变量等。
Bracket notation is open ended. It uses a string but you can produce the string using any legal js code. You may specify the string as literal (though in this case dot notation would read easier) or use a variable or calculate in some way.
括号表示法是开放的。它使用一个字符串,但是您可以使用任何合法的js代码生成字符串。您可以将字符串指定为文字(虽然在这种情况下点符号更容易阅读),或者使用变量或以某种方式计算。
So, these all set the myObj property named prop1 to the value Hello:
这些都将myObj属性prop1设为值Hello:
// quick easy-on-the-eye dot notation
myObj.prop1 = "Hello";
// brackets+literal
myObj["prop1"] = "Hello";
// using a variable
var x = "prop1";
myObj[x] = "Hello";
// calculate the accessor string in some weird way
var numList = [0,1,2];
myObj[ "prop" + numList[1] ] = "Hello";
Pitfalls:
陷阱:
myObj.[xxxx] = "Hello"; // wrong: mixed notations, syntax fail
myObj[prop1] = "Hello"; // wrong: this expects a variable called prop1
tl;dnr: If you want to compute or reference the key you must use bracket notation. If you are using the key explicitly, then use dot notation for simple clear code.
如果你想计算或引用这个键,你必须使用方括号表示法。如果您显式地使用键,那么对简单的清除代码使用点符号。
Note: there are some other good and correct answers but I personally found them a bit brief coming from a low familiarity with JS on-the-fly quirkiness. This might be useful to some people.
注意:还有一些好的和正确的答案,但我个人觉得它们有点简短,因为我不太熟悉JS上飞的古怪。这可能对某些人有用。
#9
0
If you want to add fields to an object dynamically, simplest way to do it is as follows:
如果要动态地向对象添加字段,最简单的方法是:
var params= [
{key: "k1", value=1},
{key: "k2", value=2},
{key: "k3", value=3}];
for(i=0; i< params.len; i++) {
data[params[i].key] = params[i].value
}
This will create data object which has following fields:
这将创建具有以下字段的数据对象:
{k1:1, k2:2, k3:3}
#10
0
Based on the wOxxOm's answer, this is an example of use:
根据wOxxOm的答案,这是一个使用的例子:
const data = [
{"id": "z1", "val":10},
{"id": "z2", "val":20},
{"id": "z3", "val":30}
];
const obj = Object.assign.apply({}, data.map((el, i) => ({[el.id]: el.val})));
console.log(obj);