Behavior of Javascript object literals (using a variable as a key value)

Viewed 90
function addName(obj, name, value) {
return {...obj, name: value} 
}

addName({}, "Brutus", 300)

When an object literal is created with a variable used as a key why is it that the variable doesn't get used? instead when the object is returned it just returns "name: 300" instead of "Brutus: 300". Interested just on this behavior, I understand the correct way to do this is to create an object separately and then create the key with the value (obj[name] = value).

3 Answers

You need to use [] notation for computed property names otherwise the name will be initialized as the literal name used

function addName(obj, name, value) {
  return { ...obj, [name]: value}
}

console.log(addName({}, "Brutus", 300))

That's simply Javascript syntax... When initializing an object the key names are taken literally even if there is a variable of the same name.

If you'd like to keep that syntax you may be interested in computed property names (see "New notations in ECMAScript 2015" of the article linked above).

return {...obj, [name]: value} 

I think it's worth pointing out that this syntax creates a new object which copies the key/value pairs from the old object. That may or may not be important if your program relies on obj being == or === to a stored variable.

If you want to keep the same object and simply add a new property, you can always just add it on.

obj[name] = value;
return obj;

Add a [] around name

function addName(obj, name, value) {
return {...obj, [name]: value} 
}

addName({}, "Brutus", 300)
Related