0

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}]
asked Apr 30, 2018 at 18:01

3 Answers 3

1

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
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0
let account = {
 expenses: [],
 addExpense: function(description, amount){
 let addObject = {};
 addObject[description] = amount
 this.expenses.push(addObject)
 }
}
account.addExpense('Shopping', 50)
console.log(account.expenses)
answered Apr 30, 2018 at 18:13

1 Comment

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).

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.