0

I need to write a code so that result comes out as

{ username: 'Cloud', 
  species: 'sheep', 
  tagline: 'You can count on me!', 
  noises: ['baahhh', 'arrgg', 'chewchewchew'], 
  friends: [{username: 'Moo', species: 'cow'...}, {username: 'Zeny', species: 'llama'...}]
}

but my code currently prints first as the new object added onto the existing object and when I try to add another new object onto the existing object and console.log it, it replaces the last object added and only adds the new object values.

{ username: 'Cloud',
  species: 'sheep',
  tagline: 'You can count on me!',
  noises: [ 'baahhh', 'arrgg', 'chewchewchew' ],
  friends: 
   { username: 'Moo',
     species: 'cow',
     tagline: 'asdf',
     noises: [ 'a', 'b', 'c' ],
     friends: [] } }
{ username: 'Cloud',
   species: 'sheep',
   tagline: 'You can count on me!',
   noises: [ 'baahhh', 'arrgg', 'chewchewchew' ],
   friends: 
    { username: 'Zeny',
      species: 'llama',
      tagline: 'qwerty',
      noises: [ 'z', 'x', 'c' ],
      friends: [] } }

Here is my code so far. I only put animal2 = animal to write that it replaces it so that when adding another new object value it adds it into that object, not the original. Do I need to have a loop here in order to have this work?

function AnimalCreator(username, species, tagline, noises) {
  var list = { 
    username: username,
    species: species,
    tagline: tagline,
    noises: noises,
    friends: []
  };

    return list;

}

function addFriend(animal, animal2) {

    animal.friends = animal2;
    animal2 = animal;


}

var sheep = AnimalCreator('Cloud', 'sheep', 'You can count on me!', ['baahhh', 'arrgg', 'chewchewchew']);
var cow =  new AnimalCreator('Moo', 'cow', 'asdf', ['a', 'b','c']);
addFriend(sheep, cow);
console.log(sheep);
var llama = new AnimalCreator('Zeny', 'llama', 'qwerty', ['z', 'x', 'c']);
addFriend(sheep,llama);
console.log(sheep);

What am I doing wrong?

1 Answer 1

2

Your problem looks to be in addFriend(animal, animal2) where you set animal2 = animal. What I think you are trying to do is append friends which could be done like

function addFriend(animal, animal2) {
    var pastFriends=animal.friends;
    pastFriends.push(animal2);
    animal.friends = pastFriends;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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.