I have a table of data that is rendered from an object. Specifically, each row of the table is a value from the array.
I need to be able to move the object up or down in the array, depending on the button clicked.
var obj = [{
"RuleDetailID": "11624",
"AttributeValue": "172",
"Value": "Account Manager",
"IsValueRetired": "0"
}, {
"RuleDetailID": "11626",
"AttributeValue": "686",
"Value": "Agent",
"IsValueRetired": "0"
}, {
"RuleDetailID": "11625",
"AttributeValue": "180",
"Value": "Analyst",
"IsValueRetired": "0"
}, {
"RuleDetailID": "11629",
"AttributeValue": "807",
"Value": "Individual Contributor",
"IsValueRetired": "0"
}, {
"RuleDetailID": "11627",
"AttributeValue": "690",
"Value": "Senior Agent",
"IsValueRetired": "0"
}];
// Exmaple only, just rendering a table
function renderExample() {
var table = '';
for (var key in obj) {
table += "<tr><td>" + obj[key].Value + "</td><td><a href=\"#\" onClick=\"move('up', " + obj[key].RuleDetailID + ")\">Move Up</a></td><td></td><td><a href=\"#\" onClick=\"move('down', " + obj[key].RuleDetailID + ")\">Move Down</a></td></tr>";
}
return table;
}
// Move the object in the array up or down
function move(value, positionChange) {
// On run, move the object in the array up or down respectivly.
}
<table>
<tbody id="example">
<script>
document.write(renderExample())
</script>
</tbody>
</table>
Can this be done with something like lodash
or is it more of a manual approach? I tried by getting the index of the clicked item and then doing +1
or -1
accordingly to give me the new index. However, I wasn't sure what to do at that point since another item would already exist at that index.
How can I go about achieving this? Not looking for a jQuery approach, javascript or a library such as lodash
only.