简体   繁体   English

如何通过for循环填充关联数组

[英]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 ? 我怎样才能增加那个字段1计数器?

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. Obs:我不会总是有4个字段,可能会有所不同。

UPDATE 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. 我正在使用JqueryDataTable,所以我需要创建一个obj来以dinamically方式填充它。

I have an ajax that returns me a Json with the name of the columns . 我有一个ajax,它返回一个带有name of the columns Json。

["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: 然后我有另一个Ajax给我带来与Json相同的表中的DATA:

[  
{"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. Field1,Field2,FieldN取决于所选列的列数。 (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. 就像一个注释 - 在javascript中它们不被称为关联数组,它们只是对象。

option1: 选项1:

You can create an empty object, and then add the key using obj[key] : 您可以创建一个空对象,然后使用obj[key]添加obj[key]

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

option2: 选项2:

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. Obs:我不会总是有4个字段,可能会有所不同。

If dados array is an array of arrays, utilize nested for loop to iterate each element of current dados[i] array. 如果dados数组是一个数组数组,则使用嵌套for循环来迭代当前dados[i]数组的每个元素。

 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] || {};
resultado[i]["Field" + i] = dados[columns[i]];

Just use push method. 只需使用push方法。

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

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

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