简体   繁体   English

创建具有动态键值对的数组

[英]Create array with dynamic key-value pairs

i have a table in which dynamic rows are coming, so i don't know how many rows. 我有一张表格,其中有动态行,所以我不知道有多少行。 Inside a td in the rows, there is some content that needs to be registered in an array on click of a button. 行中的td内,单击按钮时需要在数组中注册一些内容。

i need to create an array with that content, but it should be in this format: 我需要创建一个包含该内容的数组,但是应该采用以下格式:

array1 = [ row1:"", row2:"abc", row3:'', row4:'', row5:'xyz' ]

here, the row1...row5 comes dynamically based on the number of rows. 在这里,row1 ... row5根据行数动态变化。 By default the value of the rows can be '', thats fine. 默认情况下,行的值可以是“”,这很好。

Thanks in advance. 提前致谢。

array1 = [ row1:"", row2:"abc", row3:'', row4:'', row5:'xyz' ]

The above will not work as it it is incorrect syntax. 上面的语法不正确,因此无法使用。 What you can do is create an array of objects and use that instead. 您可以做的是创建一个对象数组,然后使用它。

array1 = [{row1:""},{row2:"abc"}];

Or, if the row number AND value are important, this may be a better structure: 或者,如果行号AND值很重要,则这可能是一个更好的结构:

array1 = [{rowId:1, value:""}, {rowId:2, value:"abc"}];

EDIT: 编辑:

To create such a structure from an existing HTML Table, you can query for the rows and operate on each row to create the array. 要从现有的HTML表创建这种结构,您可以查询行并在每一行上进行操作以创建数组。

// Get a reference to the table element
var table = document.getElementById("table1");
// Initialise empty array
var array = [];

// Query for all the tr elements of the table (rows)
table.querySelectorAll('tr').forEach(function(row, index){
    // For each row, extract value from the requried column
    var value = row.children[0].innerText; // Assuming the value to be added is in the first column (td)
    // Insert new object into array for this row
    array.push({rowId:index, value: value});
})

console.log(array); // array will be an array of our objects

with a little modification in @Chirag Ravindra code 在@Chirag Ravindra代码中进行了一些修改

  // Get a reference to the table element
var table = document.getElementById("table1");
// Initialise empty array
var array = [];

// Query for all the tr elements of the table (rows)
    table.querySelectorAll('tr').forEach(function(row, index){
// For each row, extract value from the requried column
var value = row.children[0].innerText; // Assuming the value to be added is in the first column (td)
// Insert new object into array for this row
array["row" + index] = value;
})

console.log(array); // array will be an array of our objects

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

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