Dave's Brain

Browse - Programming Tips - javaScript: how can I assign the value of one object to another?

Date: 2018apr6
Language: javaScript
Keywords: assign, copy

Q.  javaScript: how can I assign the value of one object to another?

A.  This does NOT work:

two = one; // WRONG!
Because you don't copy the fields. But this works:
const assignObject = function(dest, src) { for (var k in src) { dest[k] = src[k]; } } assignObject(two, one);
There is a builtin
Object.assign(target, ... sources);
But it doesn't work on all browsers. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

Add a comment

Sign in to add a comment
Copyright © 2008-2018, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.