Assign multiple values to keys of objects

Viewed 1486

I have to add multiple key-value pairs to an object.

I have an object called hello.

I know I have to do this to add key-value pairs to hello:

hello['a'] = 1;
hello['b'] = 2;
hello['c'] = 3;

The result will be hello = {'a':1, 'b':2, 'c':3}

I know we can do this to declare variables:

let [a,b,c] = [1,2,3];

In this case 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?

3 Answers

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

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

const hello = {}
hello["a"] = 1
hello["b"] = 2
hello["c"] = 3

const [a, b, c] = Object.values(hello)

console.log(a, b, c)

If you can use jQuery (because you added the jQuery tag), this will do:

$.extend(hello, {a:1, b:2, c:3})
Related