[英]Assign multiple values to keys of objects
I have to add multiple key-value pairs to an object.我必须向一个对象添加多个键值对。
I have an object called hello
.我有一个名为hello
的对象。
I know I have to do this to add key-value pairs to hello
:我知道我必须这样做才能将键值对添加到hello
:
hello['a'] = 1;
hello['b'] = 2;
hello['c'] = 3;
The result will be hello = {'a':1, 'b':2, 'c':3}
结果将是hello = {'a':1, 'b':2, 'c':3}
I know we can do this to declare variables:我知道我们可以这样做来声明变量:
let [a,b,c] = [1,2,3];让 [a,b,c] = [1,2,3];
In this case a=1, b=2, c=3
在这种情况下a=1, b=2, c=3
Is there an easy way like declaring variables to add key-value pairs to the object?有没有像声明变量这样的简单方法来向对象添加键值对?
I know this is an error:我知道这是一个错误:
hello['a', 'b', 'c'] = [1,2,3]
Is there a one-line way to add key-value pairs to an object?有没有一种将键值对添加到对象的单行方法?
You could do something like this:你可以这样做:
hello = {
...hello,
a: 1,
b: 2,
c: 3
}
Note that this would create a new object reference on hello
请注意,这将在hello
上创建一个新的对象引用
You could use destructing assignment for object您可以对对象使用析构赋值
const hello = {} hello["a"] = 1 hello["b"] = 2 hello["c"] = 3 const { a, b, c } = hello console.log(a, b, c)
Or use destructing assignment for array, provided that you use Object.values
to get the array of values from that object或者对数组使用析构赋值,前提是您使用Object.values
从该对象获取值数组
const hello = {} hello["a"] = 1 hello["b"] = 2 hello["c"] = 3 const [a, b, c] = Object.values(hello) console.log(a, b, c)
如果您可以使用 jQuery(因为您添加了 jQuery 标签),这将执行以下操作:
$.extend(hello, {a:1, b:2, c:3})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.