4

Is there a short-hand to do the following:

let o = {}
o['a'] = 1;
o['b'] = 2;

For example, either:

let o = {}
o.update({'a': 1, 'b': 2})

Or:

let o = {'a': 1, 'b': 2}

1 Answer 1

6

Object.assign can achieve it.

const o = { original: 'orig' };
Object.assign(o, {'a': 1, 'b': 2});

console.log(o);

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

6 Comments

thanks, why do you declare it as const in the above case? Wouldn't the updating of the object make it 'un-const' ?
const indicates that the variable won't be reassigned - that o = somethingElse won't happen later. It's good practice to use const to declare variables when possible (which it is, 95% of the time) to make code more readable. Reassignment is not the same thing as mutation. Mutation assigns to a property of the object, reassignment changes what the whole variable name points to. const only prohibits reassignment.
thanks, that's a really helpful explanation. By the way, to look up all the properties/methods of an object, how do you normally do that? For example in python I'll do something like: dir(set()) and get ['pop', 'remove', ...].
Object.keys usually. If you want the values too, Object.entries. Only values: Object.values. Non-enumerable properties too (rare): Object.getOwnPropertyNames. Properties that are non-enumerable and prototypal: recursive Object.getOwnPropertyNames
Do you have to enumerate them in a for loop in order to read them? For example, if I just do: console.log(Object.keys, Object.values, Object.values); it prints [Function: keys] [Function: values] [Function: values].
|

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.