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?

Teerapat
  • 112
  • 2
  • 7
  • 1
    Possible duplicate of [How to add an object to an array](https://stackoverflow.com/questions/6254050/how-to-add-an-object-to-an-array) – Mohammad Usman Sep 27 '18 at 06:57

4 Answers4

1
const addExpense = (expense) => {
  account.expenses.push(expense)
}
// use like this
addExpense({ description: 'Rent', amount: 1000 })
addExpense({ description: 'Coffee', amount: 2.5 })
Mettin Parzinski
  • 838
  • 1
  • 7
  • 13
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);
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62
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
HolgerJeromin
  • 2,201
  • 20
  • 21
0
const account = {
    name: "David Reallycool",
    expenses: []
}

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


addExpense("Test", 500);

console.log(account);
Chayan
  • 604
  • 5
  • 12