If you define an object like this in JavaScript, the key will always be a string – in your case a _name. To assign a dynamic variable as a key to an object, you'll need to use the bracket notation []. The value, however, is evaluated as an expression. In your case, _age is evaluated, because it's a value and not a key.
You could easily fix with e.g. this example:
function addValues(_arr, _name, _age){
var object = {};
object[_name] = {
age: _age
};
_arr.push(object);
}
These are many ways to declare an object in JavaScript:
Inline Declaration:
var object = {
_name: '123'
};
→ _name will always be a constant string.
Dot notation:
var object = {};
var object._name = '123';
→ In the dot notation, _name will also always be a constant string.
Bracket Notation:
var object = {};
var object[_name] = '123';
→ In the bracket notation, _name is an evaluated expression. In this case, a variable name _name. You could also pass a string by using object['_name'].
Computed property names:
As the other answers have pointed out, with ES6 (a newer version of JavaScript, which is not fully supported by all browsers, but can be transpiled to ES5), you could also use computed property names:
var object = {
[_name]: '123'
};
→ In this notation, the _name will be evaluated and its value will be the key in this object. Keep in mind, that you won't have IE support without transpiling this snippet.