繁体   English   中英

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

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

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

我希望将“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. object创建后,添加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);
      }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM