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

查看:118
本文介绍了使用变量作为名称将属性添加到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 ofmyId,我希望 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

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

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