使用变量作为名称,将属性添加到JavaScript对象中?

发布于 2025-01-26 21:14:43 字数 516 浏览 3 评论 0原文

我正在使用jQuery将项目从DOM中拉出,并希望使用DOM元素的ID在对象上设置属性。

示例

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

如果from tromdom包括一个元素,上面有id“ myid”,我希望obj具有名为“ myid”的属性。以上给我name

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

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.

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.

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(13

飘过的浮云 2025-02-02 21:14:43

您可以使用此等效语法:

obj[name] = value

示例

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

使用ES6功能:

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

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

You can use this equivalent syntax:

obj[name] = value

Example:

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

or with ES6 features:

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

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

揽月 2025-02-02 21:14:43

注释在对象声明中直接执行此操作:

var obj = {
  [key]: value
}

使用 ecmascript 2015 您可以使用括号 >键可以是返回值的任何形式的表达式(例如变量):

var obj = {
  ['hello']: 'World',
  [x + 2]: 42,
  [someObject.getId()]: someVar
}

With ECMAScript 2015 you can do it directly in object declaration using bracket notation:

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
}
泪是无色的血 2025-02-02 21:14:43

您甚至可以列出这样的对象列表

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

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);
});
冰魂雪魄 2025-02-02 21:14:43

有两种不同

  • 符号
  • 访问对象属性的 em>

dot符号快速且容易,但是您必须明确使用实际属性名称。没有替换,变量等

。它使用字符串,但您可以使用任何法律JS代码生成字符串。您可以将字符串指定为文字(尽管在这种情况下,点符号将读取更容易)或以某种方式使用变量或计算。

因此,所有这些都将 myobj 属性属于 prop1 hello> 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";     

陷阱:

myObj.[xxxx] = "Hello";      // wrong: mixed notations, syntax fail
myObj[prop1] = "Hello";      // wrong: this expects a variable called prop1

tl; dnr :如果您要计算或引用您必须使用支架符号的键。如果您要明确使用密钥,请使用 dot note 进行简单的清除代码。

注意:还有其他一些好的和正确的答案,但我个人发现它们有点简短,这是对JS在正式怪异的熟悉程度较低的情况。这对某些人可能很有用。

There are two different notations to access object properties

  • Dot notation: myObj.prop1
  • Bracket notation: 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.

So, these all set the myObj property named prop1 to the value 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.

盗琴音 2025-02-02 21:14:43

使用Lodash,您可以创建像这样的新

obj = _.set({}, key, val);

对象这样:

var existingObj = { a: 1 };
_.set(existingObj, 'a', 5); // existingObj will be: { a: 5 }

如果要在路径中使用dot(“。”),应该小心,因为lodash可以设置层次结构:

_.set({}, "a.b.c", "d"); // { "a": { "b": { "c": "d" } } }

With lodash, you can create new object like this _.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:

_.set({}, "a.b.c", "d"); // { "a": { "b": { "c": "d" } } }
爱你不解释 2025-02-02 21:14:43

首先,我们需要将密钥定义为变量,然后我们需要将键分配为键作为对象。

var data = {key:'dynamic_key',value:'dynamic_value'}
var key = data.key;
var obj = { [key]: data.value}
console.log(obj)

First we need to define key as variable and then we need to assign as key as object., for example

var data = {key:'dynamic_key',value:'dynamic_value'}
var key = data.key;
var obj = { [key]: data.value}
console.log(obj)

笑脸一如从前 2025-02-02 21:14:43

与主题有关,而不是专门针对jQuery。我在EC6 React项目中使用了这一点,也许可以帮助某人:

this.setState({ [`${name}`]: value}, () => {
      console.log("State updated: ", JSON.stringify(this.state[name]));
    });

PS:请注意引用角色。

Related to the subject, not specifically for jquery though. I used this in ec6 react projects, maybe helps someone:

this.setState({ [`${name}`]: value}, () => {
      console.log("State updated: ", JSON.stringify(this.state[name]));
    });

PS: Please mind the quote character.

不可一世的女人 2025-02-02 21:14:43

如果要动态地将字段添加到对象,最简单的方法如下:

let params = [
  { key: "k1", value: 1 },
  { key: "k2", value: 2 },
  { key: "k3", value: 3 },
];
let data = {};

for (let i = 0; i < params.length; i++) {
  data[params[i].key] = params[i].value;
}

console.log(data); // -> { k1: 1, k2: 2, k3: 3 }

If you want to add fields to an object dynamically, simplest way to do it is as follows:

let params = [
  { key: "k1", value: 1 },
  { key: "k2", value: 2 },
  { key: "k3", value: 3 },
];
let data = {};

for (let i = 0; i < params.length; i++) {
  data[params[i].key] = params[i].value;
}

console.log(data); // -> { k1: 1, k2: 2, k3: 3 }
匿名的好友 2025-02-02 21:14:43

随着ES2015 计算属性名称 OP的代码归结为:

var obj = Object.assign.apply({}, $(itemsFromDom).map((i, el) => ({[el.id]: el.value})));

With the advent of ES2015 Object.assign and computed property names the OP's code boils down to:

var obj = Object.assign.apply({}, $(itemsFromDom).map((i, el) => ({[el.id]: el.value})));
岁吢 2025-02-02 21:14:43

AjavaScript有两种用于获取JavaScript对象属性的注释:

obj = {};

1)(。)注释obj.id
仅当对象已经具有名称“ ID” 2)([])注释(例如)的属性时才能起作用

。 OBJ [ID]在此处,如果对象没有任何名称'ID'的属性,则将创建一个带有名称“ ID”的新属性。

因此,对于以下示例:

编写OBJ [name]时,将始终创建一个新属性。
如果该属性已经以相同的名称存在,则它将覆盖它。

const obj = {}
    jQuery(itemsFromDom).each(function() {
      const element = jQuery(this)
      const name = element.attr('id')
      const value = element.attr('value')
      // This will work
      obj[name]= value;
    })

ajavascript have two type of annotation for fetching javascript Object properties:

Obj = {};

1) (.) annotation eg. Obj.id
this will only work if the object already have a property with name 'id'

2) ([]) annotation eg . Obj[id] here if the object does not have any property with name 'id',it will create a new property with name 'id'.

so for below example:

A new property will be created always when you write Obj[name].
And if the property already exist with the same name it will override it.

const obj = {}
    jQuery(itemsFromDom).each(function() {
      const element = jQuery(this)
      const name = element.attr('id')
      const value = element.attr('value')
      // This will work
      obj[name]= value;
    })
做个少女永远怀春 2025-02-02 21:14:43

如果您有对象,则可以制作钥匙数组,而不是映射,并从以前的对象键和值创建新对象。

Object.keys(myObject)
.map(el =>{
 const obj = {};
 obj[el]=myObject[el].code;
 console.log(obj);
});

If you have object, you can make array of keys, than map through, and create new object from previous object keys, and values.

Object.keys(myObject)
.map(el =>{
 const obj = {};
 obj[el]=myObject[el].code;
 console.log(obj);
});
嘿咻 2025-02-02 21:14:43

ObjectName.NewProperty = value;

objectname.newProperty = value;

太傻旳人生 2025-02-02 21:14:43
const data = [{
    name: 'BMW',
    value: '25641'
  }, {
    name: 'Apple',
    value: '45876'
  },
  {
    name: 'Benz',
    value: '65784'
  },
  {
    name: 'Toyota',
    value: '254'
  }
]

const obj = {
  carsList: [{
    name: 'Ford',
    value: '47563'
  }, {
    name: 'Toyota',
    value: '254'
  }],
  pastriesList: [],
  fruitsList: [{
    name: 'Apple',
    value: '45876'
  }, {
    name: 'Pineapple',
    value: '84523'
  }]
}

let keys = Object.keys(obj);

result = {};

for(key of keys){
    let a =  [...data,...obj[key]];
    result[key] = a;

}
const data = [{
    name: 'BMW',
    value: '25641'
  }, {
    name: 'Apple',
    value: '45876'
  },
  {
    name: 'Benz',
    value: '65784'
  },
  {
    name: 'Toyota',
    value: '254'
  }
]

const obj = {
  carsList: [{
    name: 'Ford',
    value: '47563'
  }, {
    name: 'Toyota',
    value: '254'
  }],
  pastriesList: [],
  fruitsList: [{
    name: 'Apple',
    value: '45876'
  }, {
    name: 'Pineapple',
    value: '84523'
  }]
}

let keys = Object.keys(obj);

result = {};

for(key of keys){
    let a =  [...data,...obj[key]];
    result[key] = a;

}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文