skip to Main Content

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

2

Answers


  1. 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)
    Login or Signup to reply.
  2. Here couple of ways you can do, see my comments.

    1. one way is as suggested by @charlietlf.
    2. After object creation, add the 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);
          }
        }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search