如何使用变量作为名称将属性添加到JavaScript对象中
在JavaScript中,您可以使用变量作为名称动态地将属性添加到对象中。这使您能够根据运行时的值创建灵活和动态的对象,增强代码的可重用性和适应性。
有几种方法可以使用变量作为名称将属性添加到JavaScript对象中:
- 使用点符号
- 使用Object.assign()
- 使用ES6计算属性名称
方法1:使用点符号
使用带有方括号的点符号,您可以使用变量作为名称,将属性添加到JavaScript对象中,使其可以直接通过对象进行访问和修改。
示例: 在此示例中,Object对象1具有属性firstname和lastname。我们使用点符号添加一个名为age且值为25的属性。
let object1 =
{ firstname: "Romy", lastname: "Kumari" };
// Step 1: Define the property name and value
const newPropertyName = 'age';
const newPropertyValue = 25;
// Step 2: Add the new property using dot notation
object1[newPropertyName] = newPropertyValue;
// Step 3: Access and
//display the updated object
console.log(object1);
输出
{ firstname: 'Romy', lastname: 'Kumari', age: 25 }
方法2:使用Object.assign()
使用Object.assign(),通过合并现有的object1和新属性{ [newPropertyName]: newPropertyValue }来创建新对象。原始对象保持不变。
示例:
let object1 = { firstname: "Romy", lastname: "Kumari" };
// Step 1: Define the property name and value
const newPropertyName = 'age';
const newPropertyValue = 25;
// Step 2: Add the new property using Object.assign()
const updatedObject =
Object.assign({}, object1,
{ [newPropertyName]: newPropertyValue });
// Step 3: Access and display the updated object
console.log(updatedObject);
输出
{ firstname: 'Romy', lastname: 'Kumari', age: 25 }
方法3:使用ES6计算属性名称
ES6引入了计算属性名称,允许您在定义对象时直接使用变量来设置属性名称。
示例: 在这个示例中,通过展开object1的属性并添加一个名为’age’且值为25的属性来创建一个新对象。
const propertyName = 'age';
const propertyValue = 25;
const object1 =
{ firstname: "Romy", lastname: "Kumari" };
// Add the new property using ES6 Computed Property Names
const updatedObject = {
...object1,
[propertyName]: propertyValue,
};
// Access and display the updated object
console.log(updatedObject);
输出
{ firstname: 'Romy', lastname: 'Kumari', age: 25 }