简体   繁体   中英

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.

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. 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:

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.

// 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

  // 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

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