I have a two pieces of data I am working with to ultimately generate an HTML table.
Data: This is the core data that would come from a database call.
UserColumns: This defines which order the table columns will be in. The fieldSource in this object will align with the key names in the data object.
// Define the core data we will be working with. Assumed this comes from a database,
var data = [{
FirstName: 'Joe',
LastName: 'Jones',
Age: 21,
Location: 'Arizona',
Color: 'Red', // Not defined in the column structure, therefore is not included in output
Order: 1
},
{
FirstName: 'Tim',
LastName: 'Bob',
Age: 25,
Location: 'California',
Color: 'Blue',
Order: 3
},
{
FirstName: 'Sally',
LastName: 'Smith',
Age: 29,
Location: 'Florida',
Color: 'Green',
Order: 2
}
];
// Defines the columns the user wants to include in their table output as well as their order
var userColumns = [{
FieldID: 1,
FieldSource: 'FirstName',
FieldName: 'First Name',
Order: 2
},
{
FieldID: 2,
FieldSource: 'LastName',
FieldName: 'Last Name',
Order: 1
},
{
FieldID: 3,
FieldSource: 'Age',
FieldName: 'Age',
Order: 4
},
{
FieldID: 4,
FieldSource: 'Location',
FieldName: 'Location',
Order: 3
}
];
/*
Loop over the data and order the content in the desired column order.
*/
function generateTableRows() {
let output = [];
for (var j = 0; j < data.length; j++) {
// Need to re-order the object keys based on the "User Columns".
// This also needs to ensure the the table rows are in the correct order based on the "Order" property
console.log(data[j]);
}
}
In the example code above, the keys in data need to be re-ordered to match the order defined in the userColumns object.
End goal here is that the user will see the table of data in their desired view (columns in the defined order).
How can I go about putting the keys in a specific order and will they remain that way in the object or can they change?
I need to essentially take an object of data and then output re-arrange it so that its in the user defined order when it comes time to render a table.
Here is a fiddle of the full task at hand I am trying to workout: https://jsfiddle.net/os48s1ne/
userColumnsby theOrderproperty. Then loop throughuserColumnsand access the corresponding property ofdata[j].Set()developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…