简体   繁体   中英

How to populate associative array through for loop

I need to create this kind of element inside my array:

{ Field1: "2011/04/23", Field2: 8, Field3: "Adam", Field4: "Den"},  
{ Field1: "2011/03/25", Field2: 6, Field3: "Honey",Field4: "Singh"}   

How may I increasce that field 1 counter ?

var resultado = [];
    for(i=0;  i< dados.length; i++){                
        resultado[i] = { "Field"+i: dados[columns[i]]};
    }  

If I try to do like above, it gives me an error saying I can't use the + character. How may I achieve my goal ?

Obs: i'll not always have 4 fields, it may vary.

UPDATE

Following the answers I could achieve part of what I need, now the code is like this:

var resultado = [];
    for(i=0;  i< dados.length; i++){                
        resultado[i] = { ["Field"+i]: dados[columns[i]]};
    }    

But I'm not managing to write all of that in a single position of the array.
How may I get this:

var results = [
      {
       Field1: "2011/04/23",
       Field2: 8,
       Field3: "Adam",
       Field4: "Den"  
      }, //First Element  

      {
       Field1: "2011/03/25",
       Field2: 6,
       Field3: "Honey",
       Field4: "Singh"  
      } //Second Element
    ];  

I'm using JqueryDataTable, so I need to create an obj to populate it dinamically.

I have an ajax that returns me a Json with the name of the columns .

["id_localidade","cod_munic","id_bairro","id_endereco"]  
//These are column names that I need to use later.  

Then I have another Ajax to bring me the DATA from this same table as a Json:

[  
{"id_bairro":"1","dsc_bairro":"PONTE DOS CARVALHOS"},  
{"id_bairro":"2","dsc_bairro":"CHARNECA"},  
{"id_bairro":"3","dsc_bairro":"SAO FRANCISCO"},  
{"id_bairro":"4","dsc_bairro":"ROSARIO"}  
]  

So now I need to use these two arrays and create the this:

{ Field1: "2011/04/23", Field2: 8, Field3: "Adam", Field4: "Den"},   

Where Field1, Field2, FieldN will depend on how many columns the selected column has. (As I have the name of those columns I just need to count it).

What I tried so far (without success):

var nFields   = Object.keys(dados[0]).length;//Number of columns
var nElements = dados.length; //Number of registers

var resultado = [];
for(i=1;  i<= nElements; i++){
   for(j=0; j < nFields; j++){
      var temp = [];
      temp.push({ ["Field"+ (j+1)]: dados[j][ columns[j]['sTitle'] ] });
      resultado = temp;
   }                
}

Just as a note - in javascript they are not called associative arrays, they are just objects.

option1:

You can create an empty object, and then add the key using obj[key] :

var resultado = [];
for(i=0;  i< dados.length; i++){                
    resultado[i] = {};
    resultado[i]["Field"+i] = dados[columns[i]]
}

option2:

You can create the name of the key before using it:

var resultado = [];
for(i=0;  i< dados.length; i++){                
    key = "Field"+i
    resultado[i] = {key: dados[columns[i]]};
}

You can use brackets to produce a computed name for a property of an object.

Obs: i'll not always have 4 fields, it may vary.

If dados array is an array of arrays, utilize nested for loop to iterate each element of current dados[i] array.

 var dados = [ [0, 1, 2], [3, 4], [5, 6, 7, 8] ]; var resultado = []; var prop = "Field"; for (var i = 0; i < dados.length; i++) { resultado[i] = {}; for (var n = 1; n < dados[i].length; n++) { resultado[i][prop + n] = dados[i][n - 1]; } } console.log(resultado); 

You could use a default object, if resultado[i] is not set and use bracket notation for the access.

resultado[i] = resultado[i] || {};
resultado[i]["Field" + i] = dados[columns[i]];

Just use push method.

var resultado = [];
for(var i=0;  i< dados.length; i++){                
    resultado.push({ "Field"+i : dados[columns[i]]});
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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