Skip to content

Create new object from existing object JavaScript

  • by

In JavaScript, you can create a new object from an existing object using various methods such as Object create(), the spread operator, and Object assign(). This tutorial provides examples of how to use these methods to create a new object that inherits properties and methods from an existing object.

Create new object from existing object JavaScript example

Simple example code.

Object create()

This method creates a new object and sets its prototype to an existing object.

const person = {
  firstName: "John",
  lastName: "Doe",
  getFullName() {
    return `${this.firstName} ${this.lastName}`;
  }
};

const john = Object.create(person);

console.log(john.firstName); // "John"
console.log(john.getFullName()); // "John Doe"

Spread operator

You can also use the spread operator (...) to create a new object that contains all the properties of an existing object.

const john = { ...person };

console.log(john.firstName); // "John"
console.log(john.getFullName()); // "John Doe"

Object assign()

This method is used to copy the values of all enumerable properties from one or more source objects to a target object.

const john = Object.assign({}, person);

console.log(john.firstName); // "John"
console.log(john.getFullName()); // "John Doe"

Output:

Create new object from existing object JavaScript

Do comment if you have any doubts or suggestions on this Js object topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading