最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Object.assign( ) keyvalue syntax - Stack Overflow

programmeradmin6浏览0评论

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?

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?

Share Improve this question edited May 6, 2017 at 18:55 ibrahim mahrir 31.7k5 gold badges49 silver badges77 bronze badges asked May 6, 2017 at 18:53 David KennellDavid Kennell 1,2612 gold badges13 silver badges24 bronze badges 3
  • 1 Possible duplicate of dynamic keys for object literals in Javascript – ibrahim mahrir Commented May 6, 2017 at 18:55
  • 1 So the value of key will be used: key = "abc"; then {[key]: 55} is {"abc": 55}. – ibrahim mahrir Commented May 6, 2017 at 18:57
  • 1 basically the function does not update the given object. instead it returns a new object without referencing the old object. – Nina Scholz Commented May 6, 2017 at 18:58
Add a ment  | 

2 Answers 2

Reset to default 4

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

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

console.log(obj[3]);

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 puted 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%" }

发布评论

评论列表(0)

  1. 暂无评论