Reputation: 11
Hey I'm pretty new to coding. I've tried looking around for how to do this but am at a loss.
Below are the two functions, which are in an object.
listPeople: function () {
let array = []
return array;
// returns an array of all people for whom tasks exist
},
add: function ( name, task ) {
return this.listPeople().push( name )
},
If I run this, the add function returns 1. and will return 2 if I push two things in, and so on. What's going on here, how do i push the name variable from add into the array in listpeople?? The name variable is 'zeke' by the way.
Sorry in advance if this doesn't make sense :D
Upvotes: 1
Views: 235
Reputation: 2279
What's happening in your code is that the add
function is returning the result of the .push()
method (the new length of the array).
If your intent is to actually return the array, you should modify the add
method as follows:
add: function ( name, task ) {
var people = this.listPeople();
people.push(name);
return people;
},
Additionally, while changing listPeople
to an array property instead of a method may work better on a shallow level, I don't know what you may have planned to implement into the listPeople
method. And it may only confuse/complicate things as far as answering the question you have asked.
Upvotes: 1
Reputation: 63524
It should probably look more like this. Create an arr
property, and push objects into it from add
. You can then return that list from listPeople
.
const obj = {
arr: [],
listPeople: function() {
return this.arr;
},
add: function(name, task) {
return this.arr.push({ [name]: task });
}
}
obj.add('bob', 'Shopping');
obj.add('Betty', 'Singing');
console.log(obj.listPeople());
Upvotes: 4