JavaScript: Ways to Create New Objects from Old Objects

Updated: February 19, 2023 By: Khue Post a comment

As a web developer, you are very likely to find yourself in need of creating new objects from old ones in Javascript when either developing complex projects or just writing some code for small applications. Although the job seems simple at first, there are many pitfalls and it is easy to write the wrong code that leads to disastrous outcomes if you do not understand your Javascript objects deeply.

In this article, we’ll walk through a couple of different ways to create a truly new object from a given object in Javascript.

Using Object.assign()

The Object.assign() method allows you to properly clone a given object by copying its properties to a new object. To use it, you pass the existing object to the Object.assign() method as the first argument. Then you can specify any additional properties you want to add to the new object as additional arguments.

This approach works with both shallow objects and deeply nested objects. Let’s have a look at a quick example:

// slingacademy.com
var oldObject = {
  name: 'John',
  age: 35,
  skills: ['html', 'css', 'js'],
  contact: { email: '[email protected]', phone: 123 },
};

var newObject = Object.assign({}, oldObject, { job: 'developer' });

console.log('old object:', oldObject);
console.log('new object:', newObject);

Output:

old object: {
  name: 'John',
  age: 35,
  skills: [ 'html', 'css', 'js' ],
  contact: { email: '[email protected]', phone: 123 }
}
new object: {
  name: 'John',
  age: 35,
  skills: [ 'html', 'css', 'js' ],
  contact: { email: '[email protected]', phone: 123 },
  job: 'developer'
}

This code would create a new object called newObject that contains all the properties of the oldObject, plus the additional job property. The advantage of using the Object.assign() method is that it’s relatively simple and straightforward.

Using the Spread Operator

The spread operator is a relatively new addition to the language since ES6 and it allows you to quickly and easily create new objects from existing ones. To use it, you simply pass the existing object to the spread operator as the argument, and then you can add any additional properties you want to the new object.

Example:

// slingacademy.com
var oldProduct = {
  name: 'Laptop',
  price: 50000,
  brand: 'Dell',
  description: { weight: '1.6kg', screen: 15.6, color: 'silver'},
};

// clone the object without adding new properties
var newProduct1 = { ...oldProduct };
console.log('newProduct1', newProduct1);

// clone the object and add new properties
var newProduct2 = { ...oldProduct, freeShip: true };
console.log('newProduct2', newProduct2);

Output:

newProduct1 {
  name: 'Laptop',
  price: 50000,
  brand: 'Dell',
  description: { weight: '1.6kg', screen: 15.6, color: 'silver' }
}
newProduct2 {
  name: 'Laptop',
  price: 50000,
  brand: 'Dell',
  description: { weight: '1.6kg', screen: 15.6, color: 'silver' },
  freeShip: true
}

This code would create 2 new objects called newProduct1 (identical to the source object) and newProduct2 (contain all the properties of the old object plus the additional freeShip property).

As you can see, the code is short and concise.

Using JSON Trick

This is a classic trick to clone a Javascript object correctly and is still widely used today because of its reliability in all environments, from Node.js to browsers, and from legacy to modern browsers. We have 2 steps:

  1. Generate JSON string from the old object with JSON.stringify()
  2. Use JSON.parse() to produce the new object

Example:

// slingacademy.com
var oldObject = {
  name: 'John Doe',
  age: 35,
  childArray: ['red', 'blue', 'yellow'],
  childObject: {
    'location': 'USA',
    'state': 'CA'
  },
};

var json = JSON.stringify(oldObject);
var newObject = JSON.parse(json);

// add new property to the cloned object
newObject.newProperty = 'new property';

console.log(newObject);

Output:

{
  name: 'John Doe',
  age: 35,
  childArray: [ 'red', 'blue', 'yellow' ],
  childObject: { location: 'USA', state: 'CA' },
  newProperty: 'new property'
}

Conclusion

Creating a new object from an existing object in Javascript can be a tricky task but it’s unavoidable and you will have to deal with it sooner or later. In this article, we’ve covered different ways of doing so. We’ve looked at the Object.assign() method, the spread operator, and the JSON old-school trick. There are still other techniques, but these are the three best and most popular.

Happy coding and have a nice day!