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

问题描述

是否可以使用“ 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'),};

我尝试了上面的代码获取以下错误:未捕获的SyntaxError:意外的令牌'[' 谢谢

解决方法

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

简单的例子:

let obj = {};

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

console.log(obj)

,

您可以通过以下几种方式查看我的评论。

  1. 一种方法是@charlietlf建议的。
  2. 创建对象后,添加键/值
    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);
      }
    }