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?

asked Sep 27, 2018 at 6:55
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 })
answered Sep 27, 2018 at 6:58
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);
answered Sep 27, 2018 at 7:02

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

answered Sep 27, 2018 at 6:59

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
answered Sep 27, 2018 at 7:00

Comments

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.