如何在 javascript 中的关联数组上使用数组索引生成数组键

How to generate array key using array index in for on the associative array in javascript

是否可以使用“for”中的数组索引生成数组键来创建关联数组?

我希望将“for”中索引数组中的值用作关联数组中的键

制作关联数组要获取值的示例代码在***号中间:

                 if(data.status == 422){
                    let msg = data.responseJSON.errors;
                    let msgObject = Object.keys(msg);
                    
                    for (let i = 0; i < msgObject.length; i++) {
                        if (msg[msgObject[i]]) {
                            let msgObjectIndex = msgObject[i];

                            let columnIndex = {
                                       ||
                                       \/
                                ***msgObject[i]*** : column[msgObject[i]]
                                       /\
                                       ||
                            };
                            console.log(columnIndex);
                            
                        }
                    }
                }else {
                    alert('Please Reload to read Ajax');
                    console.log("ERROR : ", e);
                    }
                },

则变量列为:

let column = {
            'nama_paket' : $('.edit_error_nama_paket'), 
            'tipe_berat' : $('.edit_error_tipe_berat'), 
            'harga'      : $('.edit_error_harga'), 
            'id_service' : $('.edit_error_id_service'),
        };

我尝试了上面的代码得到了以下错误:Uncaught SyntaxError: Unexpected token '[' 谢谢

您可以使用 [] 语法生成计算的 属性 名称

简单示例:

let obj = {};

['a','b','c'].forEach((e,i) => {
  let computed = {[e]:i};
  Object.assign(obj, computed) 
})

console.log(obj)

这里有几种方法,请看我的评论。

  1. 一种方法是@charlietlf 所建议的。
  2. 创建对象后,添加key/value
    let msg = data.responseJSON.errors;
    let msgObject = Object.keys(msg);
    
    for (let i = 0; i < msgObject.length; i++) {
      if (msg[msgObject[i]]) {
        let msgObjectIndex = msgObject[i];
    
        const newKey1 = `MyNewKey${2 + 3}`; // sample
        let columnIndex = {
          // One way is
          [newKey1]: column[msgObject[i]],
        };
    
        // Alternatively, we can add the generated key and value to obj
        const newKey2 = msgObject[i];
        //  or something like newKey2 = `MyKey${msgObject[i]}`
        columnIndex[newKey2] = column[msgObject[i]];
    
        console.log(columnIndex);
      }
    }