I'm trying to add an object to the expense array using the addExpense method.
const account = {
expenses: [],
addExpense: function(description, amount){
let addObject = {
description : amount
}
this.expenses.push(addObject)
}
}
account.addExpense('Shopping', 50)
console.log(account.expenses)
I get no errors but the result gives me an object using the parameter name and not the actual string value, 'Shopping'. The amount argument works fine.
[{"description": 50}]
3 Answers 3
Use computed property names - an expression in brackets that evaluates to the key name (the description value in this case):
let addObject = {
[description] : amount
}
Demo:
const account = {
expenses: [],
addExpense: function(description, amount){
let addObject = {
[description] : amount
}
this.expenses.push(addObject)
}
}
account.addExpense('Shopping', 50)
console.log(account.expenses)
answered Apr 30, 2018 at 18:03
Ori Drori
196k32 gold badges243 silver badges233 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
Right now, you are setting the "description" property statically. You want a computed property name, like so:
let addObject = {
[description] : amount
}
Full Example:
const account = {
expenses: [],
addExpense: function(description, amount){
let addObject = {
[description] : amount
}
this.expenses.push(addObject)
}
}
account.addExpense('Shopping', 50)
console.log(account.expenses)
answered Apr 30, 2018 at 18:03
mhodges
11.2k2 gold badges32 silver badges48 bronze badges
Comments
let account = {
expenses: [],
addExpense: function(description, amount){
let addObject = {};
addObject[description] = amount
this.expenses.push(addObject)
}
}
account.addExpense('Shopping', 50)
console.log(account.expenses)
1 Comment
mhodges
const =/= immutability. const merely says that the variable may not be reassigned, it has nothing to do with the value (in regards to object types).
lang-js