我有这个代码。 我想使用其他对象内的数组的值动态设置对象
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 ....
如何设置上面这样的对象的变量值?
最佳答案
您可以使用对象的[]
表示法。
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);
关于javascript - 在 javascript 对象内使用数组并动态使用数组值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27061707/