javascript - 在 javascript 对象内使用数组并动态使用数组值

标签 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 ....

如何设置上面这样的对象的变量值?

最佳答案

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

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/

相关文章:

javascript - 如何在 Next.js 路由器中取消绑定(bind) beforePopState 绑定(bind)?

javascript - uwp javascript x-ms-webview webkitfullscreenchange 事件

javascript - 咕噜 Jade 编译

javascript - jquery 中的全局变量没有给出输出

javascript - 回调 hell ,厄运金字塔,node.js

javascript - 重新声明变量时遇到的问题 (JS)

javascript - 在javascript中使用相同的id获取不同的值

php - 使用 jQuery AJAX 传递复选框数据

javascript - Facebook SDK 错误 : init not called with valid version

javascript - 我如何让一个 div 从互联网而不是从缓存中获取它的背景图像?