create a new object from existing object javascript code example

Example 1: copy object javascript

var x = {key: 'value'}
var y = JSON.parse(JSON.stringify(x))

//this method actually creates a reference-free version of the object, unlike the other methods
//If you do not use Dates, functions, undefined, regExp or Infinity within your object

Example 2: create nodejs new object

let Person = function (firstName, lastName, email) {

    this.firstName = firstName;
    this.lastName = lastName;
    this.email = email;
}

let PersonBuilder = function () {

    let firstName;
    let lastName;
    let email;

    return {
        setFirstName: function (firstName) {
            this.firstName = firstName;
            return this;
        },
        setLastName: function (lastName) {
            this.lastName = lastName;
            return this;
        },
        setEmail: function (email) {
            this.email = email;
            return this;
        },
        info: function () {
            return `${this.firstName} ${this.lastName}, ${this.email}`;
        },
        build: function () {
            return new Person(firstName, lastName, email);
        }
    };
};

var person = new PersonBuilder().setFirstName('John').setLastName('Doe')
    .setEmail('[email protected]');
console.log(person.info());

Example 3: create new object from existing object javascript

// With ES6 CLASSES
class User {
   constructor(firstName, lastName, dateOfBirth) {
      this.firstName = firstName;
      this.lastName = lastName;
      this.dateOfBirth = dateOfBirth;

      this.getName = function(){
          return "User's name: " + this.firstName + " " + this.lastName;
      }
   }
}

var user001 = new User("John", "Smith", 1985);

// With Object.create()
var user001 = {
   firstName: "John",
   lastName: "Smith",
   dateOfBirth: 1985,
   getName: function(){
      return "User's name: " + this.firstName + " " + this.lastName;
   }
};

var user002 = Object.create(user001);
    
user002.firstName = "Jane";
user002.lastName = "King";
user002.dateOfBirth = 1989;