matronator matronator - 1 year ago 75
jQuery Question

Dynamically create new element in array and update IDs of all following elements

I'm working on a timeline based journal/diary where I have array of JS objects representing individual entries. Each object has an ID based on its position in the array. The problem is that I want to be able to insert an entry into specific position in the array and then update IDs of all the entries to match their new position in the array.
Figure 1

Figure 1: There are two entries in the array with IDs 0 and 1. I click on button in the second entry (id 1) to add new entry before this one. The new entry would have an "id = 1" and all the following entries would need to update their ID to "id += 1" so there would be no duplicate IDs.

Now here's my problem. I can't seem to be able to update the IDs after (nor before) I create the new entry. Here's my code:

Create new Day object and add it to array

//currentID = ID of the entry I'm creating the new one from
//new Day(id, name, date, desc);
//daysArray is the array containing entry objects

var dayToCreate = new Day(currentID,
daysArray.splice(currentID, 0, dayToCreate); //

Update ID of all following array elements to match their new array position

var ii = daysArray.length - 1;
for (; ii > currentID; ii--) {
daysArray[ii].id = ii;
$( ".day#" + ii - 1 ).attr("id", ii); //Change ID of the DOM element

Create DOM for new entry

drawDay(currentID).insertBefore( $( ".day#" + currentID ) );

drawDay function

function drawDay(dayId) {
var $drawDiv = $( "<div class='day' id='" + daysArray[dayId].id + "'></div>" );

//Return DOM for the day
return $drawDiv;

Answer Source
var ii = daysArray.length - 1;
for (; ii > currentID; ii--) {
    daysArray[ii].id = ii;
    $( ".day#" + ii - 1 ).attr("id", ii); //Change ID of the DOM element

goes to

var daysArrayLength = daysArray.length,
    i = 0;
for (;i < daysArrayLength; i++ ) {
    daysArray[i].id = i + 1;

array.splice(start, deleteCount[, item1[, item2[, ...]]]) is changing the indexes in the array so can you just use the index as an ID?

Another approach could be to use array of 365 items one for each day of the year. This will be more inefficient though.

Or let the IDs be counted by entry but use the date here: id='" + daysArray[dayId].id + "'

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download