Reputation: 35
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}]
Upvotes: 0
Views: 84
Reputation: 666
let account = {
expenses: [],
addExpense: function(description, amount){
let addObject = {};
addObject[description] = amount
this.expenses.push(addObject)
}
}
account.addExpense('Shopping', 50)
console.log(account.expenses)
Upvotes: 0
Reputation: 11126
Right now, you are setting the "description" property statically. You want a computed property name, like so:
let addObject = {
[description] : amount
}
const account = {
expenses: [],
addExpense: function(description, amount){
let addObject = {
[description] : amount
}
this.expenses.push(addObject)
}
}
account.addExpense('Shopping', 50)
console.log(account.expenses)
Upvotes: 0
Reputation: 193037
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)
Upvotes: 1