2013-05-07 8 views
6

Desidero aggiungere più attributi a un oggetto esistente con attributi esistenti. Esiste un modo più conciso di una riga per ogni nuovo attributo?Aggiungere più attributi a un oggetto js esistente

myObject.name = 'don'; 
myObject.gender = 'male'; 

Tutto sul MDN mostra come fare nuovi oggetti con la notazione staffa, ma gli oggetti non esistenti: biblioteca https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Working_with_Objects

+1

Si coul d creare una funzione che riceva il tuo oggetto e un oggetto con i nuovi oggetti/valori e enumera il nuovo oggetto, aggiornando quello vecchio. Sarà un po 'più conciso. 'update (obj, {name:" don ", gender:" male "})' –

risposta

5

Da How can I merge properties of two JavaScript objects dynamically?

var obj2 = {name: 'don', gender: 'male'}; 
for (var attrname in myobject) { myobject[attrname] = obj2[attrname]; } 

EDIT

essere un po 'più chiara su come si potrebbe estendere oggetto Per utilizzare questa funzione:

//Extend the protype so you can make calls on the instance 
Object.prototype.merge = function(obj2) { 
    for (var attrname in obj2) { 
     this[attrname] = obj2[attrname]; 
    } 
    //Returning this is optional and certainly up to your implementation. 
    //It allows for nice method chaining. 
    return this; 
}; 
//Append to the object constructor function so you can only make static calls 
Object.merge2 = function(obj1, obj2) { 
    for (var attrname in obj2) { 
     obj1[attrname] = obj2[attrname]; 
    } 
    //Returning obj1 is optional and certainly up to your implementation 
    return obj1; 
}; 

Usage:

var myObject1 = { One: "One" }; 
myObject1.merge({ Two: "Two" }).merge({ Three: "Three" }); 
//myObject1 is { One: "One", Two: "Two", Three: "Three", merge: function } 


var myObject2 = Object.merge2({ One: "One" }, { Two: "Two" }); 
Object.merge2(myObject2, { Three: "Three" }); 
//myObject2 is { One: "One", Two: "Two", Three: "Three" } 

Nota: Certamente potrebbe attuare una strategia di unione di conflitto flessibile a seconda delle esigenze .

3

utilizzare jQuery

jQuery.extend(myObject, { name : 'don', gender : 'male' }); 
+0

Purtroppo non posso usare jQuery. (Come in modo particolare sfortunato) Anche se questo sembra super pulito ... –

+0

Questa domanda non è taggata [tag: jQuery]. –

+0

jQuery solo per estendere un oggetto è stupido. –

4

a volte lo faccio in questo modo:

var props = { 
    name : 'don', 
    gender : 'male', 
    age : 12, 
    other : false 
}; 
for(var p in props) myObject[p] = props[p]; 
2

In ECMAscript 5 è possibile farci del defineProperties:

Object.defineProperties(myobject, { 
    name: { 
    value: 'don' 
    }, 
    gender: { 
    value: 'male' 
    } 
}); 
+0

Sfortunatamente quella sintassi è piuttosto prolissa, rendendola anche più lunga dell'originale che OP sta sperando di ottimizzare. –

+0

Sì, immagino che tu abbia ragione, questo ha più utilità quando vuoi proteggerti dalle mutazioni dei tuoi oggetti. Hehe, lo faccio sempre ... = P – JimmyRare

+0

Sono d'accordo. È una bella caratteristica, semplicemente goffa. –

-1

Il metodo .push() ha funzionato per me su un problema in una classe Codice gratuita di Camp . Non so se questo è pratico nell'applicazione reale, ma ha superato il test. Ecco cosa era a posto:

var myMusic = [ 
    { 
    "artist": "Billy Joel", 
    "title": "Piano Man", 
    "release_year": 1973, 
    "formats": [ 
     "CS", 
     "8T", 
     "LP" ], 
    "gold": true 
    }]; 

Ecco cosa ho inserito:

myMusic.push({ 
    "artist": "Metallica", 
    "title": "Ride the Lightning", 
    "release_year" : 1984, 
    "formats": [ 
     "CS", 
     "8T", 
     "LP" ] 
    } // Add record here 
); 

Ecco l'output che è visualizzato:

[ { 
    "artist": "Billy Joel", 
    "title": "Piano Man", 
    "release_year": 1973, 
    "formats": [ 
     "CS", 
     "8T", 
     "LP" ], 
    "gold": true 
    },{ 
    "artist": "Metallica", 
    "title": "Ride the Lightning", 
    "release_year" : 1984, 
    "formats": [ 
     "CS", 
     "8T", 
     "LP" ] 
    }] 
+0

Era inteso come una risposta.Il post originale chiedeva se ci fosse un modo per aggiungere più cose a un oggetto esistente in una volta. –

+3

aspetta ma aggiunge un oggetto aggiuntivo a un array. non è la stessa cosa – Julix

3

In ES6/ES2015 è possibile utilizzare il metodo Object.assign

let obj = {key1: true}; 
console.log('old obj: ', obj); 
let newObj = {key2: false, key3: false}; 

Object.assign(obj, newObj); 
console.log('modified obj: ', obj); 
Problemi correlati