使用变量作为名称向 JavaScript 对象添加属性? [英] Add a property to a JavaScript object using a variable as the name?

查看:35
本文介绍了使用变量作为名称向 JavaScript 对象添加属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 jQuery 从 DOM 中提取项目,并想使用 DOM 元素的 id 为对象设置一个属性.

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.

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
})

如果itemsFromDom 包含一个id 为myId"的元素,我希望obj 有一个名为myId"的属性.上面给了我name.

If itemsFromDom includes an element with an id of "myId", I want obj to have a property named "myId". The above gives me name.

如何使用 JavaScript 使用变量命名对象的属性?

How do I name a property of an object using a variable using JavaScript?

推荐答案

您可以使用以下等效语法:

You can use this equivalent syntax:

obj[name] = value

示例:

let obj = {};
obj["the_key"] = "the_value";

或具有 ES6 特性:

or with ES6 features:

let key = "the_key";
let obj = {
  [key]: "the_value",
};

在这两个例子中,console.log(obj) 将返回:{ the_key: 'the_value' }

in both examples, console.log(obj) will return: { the_key: 'the_value' }

这篇关于使用变量作为名称向 JavaScript 对象添加属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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