2014-11-21 39 views
1

我有這段代碼。 我想以與陣列的其它物體內部的值動態地設置對象使用JavaScript對象內的數組並動態使用數組值

var object1 = {repetidos : {}}; 
var object2 = {nombre: 'Example', precio: 'Example 2', etc...}; 

//Object with the array 
var carga = { 
    repetidos : ['nombre','precio'] 
} 

// custom function to set objects... I don't want to return nothing 
cargaDatos(object1,object2,carga); 

// Here is the function that i'm trying to code 
cargaDatos = function(object1,object2,carga){ 

    // what can i do here?. I have tried to use for loops 
    for(var key in carga){ 
     for(var key2 in key){ 
      //Here I have tried many things 
     } 
    } 
} 
////////////////////////////////////////////////////////// 
// I want set something like this inside the function 
object1.repetidos.nombre = object2.nombre; // nombre is variable 
object1.repetidos.precio = object2.precio; // precio is variable 
etc .... 

怎麼辦與變量值設定的對象,如以上?

回答

0

您可以使用[]對象的表示法。

var object1 = { 
 
    repetidos: {} 
 
}; 
 
var object2 = { 
 
    nombre: 'Example', 
 
    precio: 'Example 2' 
 
}; 
 

 
//Object with the array 
 
var carga = { 
 
    repetidos: ['nombre', 'precio'] 
 
}; 
 

 
// Here is the function that i'm trying to code 
 
var cargaDatos = function(object1, object2, carga) { 
 
    // what can i do here?. I have tried to use for loops 
 
    for (var key in carga) { 
 
    for (var key2 in carga[key]) { 
 
     // since carga[key] is an array key2 refers to the index 
 
     var actualKey2 = carga[key][key2]; 
 
     object1[key][actualKey2] = object2[actualKey2]; 
 
    } 
 
    } 
 
} 
 

 
// custom function to set objects... I don't want to return nothing 
 
cargaDatos(object1, object2, carga); 
 

 
//test 
 
console.log(object1);

+0

謝謝加比工作完美! – ns777 2014-11-21 13:09:01

0

您需要使用括號符號來動態地訪問這些對象的元素:

cargaDatos(object1,object2,carga); 

function cargaDatos(object1,object2,carga){ 
    for(var key in carga){ 
     for(var key2 in key){ 
      object1[key][carga[key][key2]] = object2[carga[key][key2]]; 
     } 
    } 
} 
console.log(object1); 

還要注意,我改變var cargaDatos = function....function cargaDatos,否則你需要之前聲明var cargaDatos你用吧。如果您只使用function cargaDatos,則在使用之前或之後聲明它並不重要。

注意:如果要動態地填滿整個object1你必須確保該元素keyobject1存在:

for(var key in carga){ 
    for(var key2 in key){ 
     if(!object1[key])object1[key] = {}; 
     object1[key][carga[key][key2]] = object2[carga[key][key2]]; 
    } 
} 
+0

謝謝Markai。它也有效,但我有一個流星異常。現在我正在尋找原因。感謝有關函數聲明的解釋 – ns777 2014-11-21 13:24:38

0

主要的事情要明白的是,你可以通過obj[key]與動態密鑰訪問對象屬性。爲了遍歷數組,你也可以使用foreach ..

cargaDatos = function(object1,object2,carga){ 
    for(var key in carga){ 
     carga[key].forEach(function(x){ 
      object1[key][x] = object2[x]; 
     }); 
    } 
} 
+0

它工作得太:)。謝謝你,pibsam – ns777 2014-11-21 13:12:02

相關問題