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}]

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)

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)

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)

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

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.