DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 966,155 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Randy Rivera
Randy Rivera

Posted on

Modifying an Array Stored in an Object

  • Take a look at the object I've provided.
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

  // Only change code above this line
}

console.log(addFriend(user, 'Pete'));
Enter fullscreen mode Exit fullscreen mode
  • 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.
  • Answer:
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) {
  userObj.data.friends.push(friend)
  return userObj.data.friends
}
Enter fullscreen mode Exit fullscreen mode
console.log(addFriend(user, 'Pete')); console will display 
[ 'Sam', 'Kira', 'Tomo', 'Pete' ]
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
vjnvisakh profile image
Visakh Vijayan

Duplicate friends :D

Visualizing Promises and Async/Await 🀯

async await

☝️ Check out this all-time classic DEV post