SyM
SyM

Reputation: 35

How to add object into an array javascript

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

Answers (3)

z0r0
z0r0

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

mhodges
mhodges

Reputation: 11126

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)

Upvotes: 0

Ori Drori
Ori Drori

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

Related Questions