Reputation: 39
My goal is to create an array of JavaScript objects and would like the output to be in a format like below:
journal = [
{
events: ["work", "ice cream", "cauliflower",
"lasagna", "touched tree", "brushed teeth"
],
squirrel: false
},
{
events: ["weekend", "cycling", "break", "peanuts",
"soda"
],
squirrel: true
}
];
The goal is to build from the following function with both given parameters (events and squirrel)
let journal = [];
function addEntry(events, squirrel) {
...........
...........
}
I wrote the code below and the output is giving me an error: "false is not a function". How can I fix that error and get the output expected? Thanks
let journal = [];
function addEntry(events, squirrel) {
journal.push(
({
events: ["work", "ice cream", "cauliflower", "lasagna", "touched tree", "brushed teeth"]
}, false)
({
events: ["weekend", "cycling", "break", "peanuts", "soda"]
}, true)
)
}
addEntry(console.log(journal));
Upvotes: 1
Views: 142
Reputation: 1156
Your syntax in is incorrect
You passed result of console.log
method to addEntry
method, this is no meaning
You used ()
in your addEntry method ({ events: [...] }, false)
, this is a syntax error, you need to push an object (wrapper by {}
, like this: ({ events: [...], squirrel : false })
This is example code:
let journal = [];
function addEntry(events) {
events.forEach(event => journal.push(event));
}
let events = [
{
events: ["work", "ice cream", "cauliflower",
"lasagna", "touched tree", "brushed teeth"
],
squirrel: false,
},
{
events: ["weekend", "cycling", "break", "peanuts",
"soda"
],
squirrel: true
}
]
addEntry(events);
console.log(journal);
Upvotes: 0
Reputation: 37755
When you push multiple values using push
you need to separate them by ,
. here you have (obj,false)()
in this format, since the comma operator returns the last operand, so you actually end up doing false()
let journal = [];
function addEntry(events, squirrel) {
journal.push(
({
events: ["work", "ice cream", "cauliflower", "lasagna", "touched tree", "brushed teeth"]
}, false),
({
events: ["weekend", "cycling", "break", "peanuts", "soda"]
}, true)
)
}
addEntry(journal);
console.log(journal)
Here if you intend to push just object you don't need wrapping ()
and also if you need more than one property in your object you can add inside object, like this
{
key: value,
key: value
}
let journal = [];
function addEntry(events, squirrel) {
journal.push({...events,squirrel})
}
addEntry({
events: ["work", "ice cream", "cauliflower", "lasagna", "touched tree", "brushed teeth"]},true);
addEntry({
events: ["weekend", "cycling", "break", "peanuts", "soda"]},false)
console.log(journal)
Upvotes: 2