Skip to content

Instantly share code, notes, and snippets.

@nnnkit
Last active January 15, 2021 01:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save nnnkit/96aebede7899004365cd3d0e88038017 to your computer and use it in GitHub Desktop.
Save nnnkit/96aebede7899004365cd3d0e88038017 to your computer and use it in GitHub Desktop.
Cloning Array and Objects
  1. Clone the array given below person into a new varibale named clonedPerson
let person = [
  {
    input: { name: 'Ryan' },
    output: { name: 'Ryan' },
  },
  {
    input: { name: { first: 'Ryan', last: 'Haskell-Glatz' } },
    output: { firstName: 'Ryan', lastName: 'Haskell-Glatz' },
  },
  {
    input: { name: 'Ryan', age: 24 },
    output: { name: 'Ryan', age: 24 },
  },
  {
    input: {
      name: { first: 'Ryan', last: 'Haskell-Glatz' },
      birthday: { year: 1993, month: 'Nov' },
    },
    output: {
      firstName: 'Ryan',
      lastName: 'Haskell-Glatz',
      birthdayYear: 1993,
      birthdayMonth: 'Nov',
    },
  },
];

// Your code goes here
  1. Write a function named cloneObject that accepts an object and returns the clone of the object
function cloneObject() {
  // your code
}

// Run the test below to check your function

let user = {
  name: 'John',
  house: 'Stark',
  sisters: ['Arya', 'Sansa'],
};
let cloned = cloneObject(user);

let person = {
  firstName: 'John',
  lastName: 'Doe',
  address: {
    street: 'North 1st',
    city: 'San Jose',
    state: 'CA',
    country: 'USA',
  },
};

let clonedPerson = cloneObject(user);

console.log(
  `The user object is ${
    user == cloned ? `not clone` : `cloned successfully 😁👑`
  }`
);
console.log(
  `The person object is ${
    person == clonedPerson ? `not clone` : `cloned successfully 😁👑`
  }`
);
  1. Clone the allBlogs variable into a new variable named allBlogsClone
var allBlogs = {
    id: 1,
    title: "Alamofire JSON Serialization",
    body: "All about serialization in Alamofire...",
    author: {
        id, 1,
        fullName: "Jeff Potter",
        username: "jpotts18"
    },
    comments: [
        {
          id: 1,
          body: "Thanks for the help Jeff, this saved me hours"
        },
        {
          id: 2,
          body: "Your welcome. I am happy to help!"
        }
    ]
}
  1. Write a function getDeepClone that accepts any array or object. It can be multiple level nested. You can use this article for help https://medium.com/javascript-in-plain-english/how-to-deep-copy-objects-and-arrays-in-javascript-7c911359b089
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment