Basic Data Structures - Modify an Array Stored in an Object

Tell us what’s happening:
So I have a question about my return line within the function. I have altered the original structure and console logged to confirm this. Yet it is not passing for some reason. I compared my solution with the one given as a last resort. why in my return statement must I list the entire path…“return userObj.data.friends”? The structure has been modified why can’t i just return the entire structure…is this because the question only wants the array(I think i just realized why lol).

Ok, I have another question. why can’t I return the result of userObj.data.friends.push(friend) in one line?

Describe your issue in detail here.

question setup:

Take a look at the object we’ve provided in the code editor. The user object contains three keys. The data key contains five keys, one of which contains an array of friends . From this, you can see how flexible objects are as data structures. We’ve started writing a function addFriend . Finish writing it so that it takes a user object and adds the name of the friend argument to the array stored in user.data.friends and returns that array.

Your code so far

let user = {
  name: 'Kenneth',
  age: 28,
  data: {
    username: 'kennethCodesAllDay',
    joinDate: 'March 26, 2016',
    organization: 'freeCodeCamp',
    friends: [
      'Sam',
      'Kira',
      'Tomo'
    ],
    location: {
      city: 'San Francisco',
      state: 'CA',
      country: 'USA'
    }
  }
};

function addFriend(userObj, friend) {
  // Only change code below this line
   

 userObj.data.friends.push(friend); 
    return userObj // question ABOUT THIS LINE 
  

// Only change code above this line
}

console.log(addFriend(user, 'Pete'));

console.log(user)


//console output{ name: 'Kenneth',
  age: 28,
  data: 
   { username: 'kennethCodesAllDay',
     joinDate: 'March 26, 2016',
     organization: 'freeCodeCamp',
     friends: [ 'Sam', 'Kira', 'Tomo', 'Pete' ],
     location: { city: 'San Francisco', state: 'CA', country: 'USA' } } }
{ name: 'Kenneth',
  age: 28,
  data: 
   { username: 'kennethCodesAllDay',
     joinDate: 'March 26, 2016',
     organization: 'freeCodeCamp',
     friends: [ 'Sam', 'Kira', 'Tomo', 'Pete' ],
     location: { city: 'San Francisco', state: 'CA', country: 'USA' } } }

You already answered your own question. But yes, the requirement is to return the friends array, not the user object.

2 Likes

why can’t I return the result of userObj.data.friends.push(friend) in one line?

Array.prototype.push() - JavaScript | MDN when in doubt, go to the docs. I’m this case, look at what array.push() actually returns - if you return that, are you returning the thing you’re being asked for?

1 Like

ahhh…I see. Thank you! I def don’t want just the length.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.