0

I have an empty array inside the object like this,

const account = {
name: "David Reallycool",
expenses: []

}

and I need to create a function to add expense into an empty array, the result I need is,

const account = {
name: "David Reallycool",
expenses: [
    {
        descrition: "Rent",
        amount: 1000
    },
    {
        description: "Coffee",
        amount: 2.50
    }
]

How can I manipulate it?

1

4 Answers 4

1
const addExpense = (expense) => {
  account.expenses.push(expense)
}
// use like this
addExpense({ description: 'Rent', amount: 1000 })
addExpense({ description: 'Coffee', amount: 2.5 })
Sign up to request clarification or add additional context in comments.

Comments

0
const account = {
    name: "David Reallycool",
    expenses: []
}

function addExpense(description, amount){
    account.expenses.push({"description": description, "amount":amount});
}


addExpense("Test", 500);

console.log(account);

Comments

0

You need to know two things for that:

  1. Changing value in array reflects the change in the original array if you are passing the array as a function parameter as it is passed by reference.
  2. You need to use push() function of Array prototype to add that object in your expenses array.

function addExpense(expensesArray, expense){
  expensesArray.push(expense);
}

const account = {
  name: "David Reallycool",
  expenses: []
};
var expense = {
  descrition: "Rent",
  amount: 1000
}
addExpense(account.expenses, expense);
var expense = {
  descrition: "Coffee",
  amount: 2.5
}
addExpense(account.expenses, expense);

console.log(account);

Comments

0

As an object (account) is transferred not as a copy you can manipulate it without problems inside your function.

function addExpenses(inputAccount){
    inputAccount.expenses = [
        {
            descrition: "Rent",
            amount: 1000
        },
        {
            description: "Coffee",
            amount: 2.50
        }
    ]
}
// will be called with
addExpenses(account);
// here account will have expenses content

Comments

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.