2

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
  • 2
    like Object.assign(hello, {'a':1, 'b':2, 'c':3});? Commented Oct 1, 2020 at 14:54
  • hello['a'] = 1;hello['b'] = 2;hello['c'] = 3; is one line Commented Oct 1, 2020 at 14:54
  • @Thomas, this works, can you add this as an answer, I can select it Commented Oct 1, 2020 at 14:57

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

0

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)

1 Comment

You've just specified the opposite of what the question asked for.
0

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.