Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object.assign( ) key / value syntax

Tags:

javascript

The following function updates an object with a new key and value:

function updateObjectWithKeyAndValue(object, key, value) {
    return Object.assign({}, object, { [key]: value })  
}

What I don't understand is why key and value look different. Why is key in brackets when value isn't?

like image 484
David Kennell Avatar asked Mar 09 '23 04:03

David Kennell


2 Answers

[key] is an ES6 computed property. Here is a basic example:

let obj = {
  [1 + 2]: 'Hello!'
};

console.log(obj[3]);
like image 93
Badacadabra Avatar answered Mar 15 '23 21:03

Badacadabra


Computed Keys

Take for example, this script using ES5:

function obj(x, y) { z = {}; z[x] = y; return z; }

If you call the function obj("weed", "sativa") you will return { weed: "sativa" }

However, you cannot apply more than one key simultaneously in this way, you have to do it for every key:

function obj(w, x, y, z) { v = {}; v[w] = x; v[y] = z; return v; }

As of ES6, you can use computed keys. What does this mean?

Instead of that, you can just do this:

function obj(x, y) { return { [x]: y }}

It may not look much smaller, but it means you can use multiple dynamic keys, like so:

function obj(w, x, y, z) { return { [w]: x, [y]: z }}

So now, doing obj("weed", "sativa", "thc", "40%") will return { weed: "sativa", thc: "40%" }

like image 31
imaxwill Avatar answered Mar 15 '23 21:03

imaxwill