Search code examples
javascriptjqueryarraysajaxassociative-array

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


Is it possible to generate array keys using the array index in the "for" to create associative arrays?

I want the values in the index array in the "for" to be used as keys in the associative array

The sample code that you want to get the value for making an associative array is in the middle of the *** sign :

                 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);
                    }
                },

then variable column is:

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

I tried the code above to get the following error: Uncaught SyntaxError: Unexpected token '[' thanks


Solution

  • You can generate computed property names with [] syntax

    Simple example:

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