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?
-
1Possible duplicate of How to add an object to an arrayMohammad Usman– Mohammad Usman2018年09月27日 06:57:14 +00:00Commented Sep 27, 2018 at 6:57
4 Answers 4
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
Mettin Parzinski
8981 gold badge7 silver badges13 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
const account = {
name: "David Reallycool",
expenses: []
}
function addExpense(description, amount){
account.expenses.push({"description": description, "amount":amount});
}
addExpense("Test", 500);
console.log(account);
Comments
You need to know two things for that:
- 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.
- You need to use
push()function ofArrayprototype to add that object in yourexpensesarray.
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
Ankit Agarwal
30.8k5 gold badges41 silver badges63 bronze badges
Comments
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
HolgerJeromin
2,52224 silver badges23 bronze badges
Comments
lang-js