I have the following data structure:
var list = [
{id: 156, next_item_position: 2, name: 'Item #1'},
{id: 157, next_item_position: 3, name: 'Item #2'},
{id: 158, next_item_position: 4, name: 'Item #3'},
{id: 159, next_item_position: 5, name: 'Item #4'},
{id: 160, next_item_position: 6, name: 'Item #5'},
{id: 161, next_item_position: 7, name: 'Item #6'},
{id: 162, next_item_position: null, name: 'Item #7'}
];
There's a property named next_item_position
, basically it should store the position of "next" item (it can be selected by user).
Now, I want to keep the "connection" between items when their order is change (we have a UI for changing positions).
So, for example:
- Item with ID (156) have
next_item_position
equals to 2 (2nd item). - The order of second item is changed from 2 to 3 (2nd to 3rd).
- Now I want item with ID (156) to point to 3rd position instead of 2nd.
My implementation looks like this:
// The magic should happens here
for(j = 0, jj = list.length; j < jj; j++) {
var next_position = list[j].next_item_position;
// Find ID of item based on its position
var item_id = defaultPositions[next_position];
// Now, find current position of "item_id"
var current_position = currentPositions.indexOf(item_id);
// And update the property
list[j].next_item_position = current_position;
}
// Update "defaults" array
defaultPositions = currentPositions;
But, unfortunately, it's not working as expected.
Fiddle: https://jsfiddle.net/fhuk31q2/6/