2015-05-28 36 views
16

Volevo fare qualcosa che sia molto diretto usando Object.assign.ES5 Object.assign equivalente

var firstObj = {name : "Saba H.", rollNo : 1}; 
var secondObj = {college : "WCE"}; 
var wholeObj = Object.assign(firstObj, secondObj); 

console.log(wholeObj); // {name : "Saba H.", rollNo : 1, college : "WCE"} 

Come Object.assign fa parte della proposta di armonia ECMAScript6 e non supportate in molti browser, è possibile fare con ES5? Se no, allora c'è qualche micro biblioteca?

+2

https://lodash.com/docs#assign sulla base della stessa - in base alla modifica, dare un'occhiata al codice sorgente lodash perché no? –

+2

in [mdn] (https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) puoi vedere polyfill – Grundy

risposta

21

In underscore.js è possibile utilizzare come,

_.extend(firstObj, secondObj); 

In jQuery, è possibile utilizzare,

$.extend({},firstObj,secondObj); 

In puro Javascipt, è possibile unire n numero di oggetti utilizzando questa funzione:

function mergeObjects() { 
    var resObj = {}; 
    for(var i=0; i < arguments.length; i += 1) { 
     var obj = arguments[i], 
      keys = Object.keys(obj); 
     for(var j=0; j < keys.length; j += 1) { 
      resObj[keys[j]] = obj[keys[j]]; 
     } 
    } 
    return resObj; 
} 
0

ho trovato un polyfill lavora per Object.assign su MDN (impressionante, grazie!):

if (typeof Object.assign != 'function') { 
    // Must be writable: true, enumerable: false, configurable: true 
    Object.defineProperty(Object, "assign", { 
    value: function assign(target, varArgs) { // .length of function is 2 
     'use strict'; 
     if (target == null) { // TypeError if undefined or null 
     throw new TypeError('Cannot convert undefined or null to object'); 
     } 

     var to = Object(target); 

     for (var index = 1; index < arguments.length; index++) { 
     var nextSource = arguments[index]; 

     if (nextSource != null) { // Skip over if undefined or null 
      for (var nextKey in nextSource) { 
      // Avoid bugs when hasOwnProperty is shadowed 
      if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) { 
       to[nextKey] = nextSource[nextKey]; 
      } 
      } 
     } 
     } 
     return to; 
    }, 
    writable: true, 
    configurable: true 
    }); 
} 
Problemi correlati