How to shallow copy the objects in JavaScript?


Underscore.js, a library of javascript, has introduced a method called _.extend() to shallow copy the objects in javascript. This method copy all of the properties in the source objects over to the destination object, and return the destination object. Here the reference is used to copy but not the duplication

syntax

_.extend(object*);

It accepts objects and shallow copy them. We can provide as many objects as we can.

Example-1

In the following example, three individual objects were copied shallowly and executed in the output.

Live Demo

<html>
<body>
<script
   src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/0.10.0/lodash.min.js"></script>
</head>
<body>
<script>
   var res = JSON.stringify(_.extend(
      {name: 'Ram', designation: "content developer"}, 
      {age: 50},
      {salary: 1200000}));
   document.write((res));
</script>
</body>
</html>

Output

{"name":"Ram","designation":"content developer","age":50,"salary":1200000}


Example-2

Live Demo

<html>
<body>
<script
   src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/0.10.0/lodash.min.js"></script>
</head>
<body>
<script>
   var res = JSON.stringify(_.extend(
      {name: 'Ram', designation: "content developer"},
      {age: 50,salary: 1200000},
      {country: "India"}));
   document.write((res));
</script>
</body>
</html>

Output

{"name":"Ram","designation":"content developer","age":50,"salary":1200000,"country":"India"}
raja
Published on 11-Jul-2019 18:55:13
Advertisements