Last active
December 27, 2015 01:29
-
-
Save shadeglare/7245720 to your computer and use it in GitHub Desktop.
How to mimicry an Object ({ }) to an Array ([]) with index rearranging
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var object = { | |
1: "lorem", | |
2: "ipsum", | |
3: "dolor", | |
4: "sit", | |
5: "amet" | |
}; | |
var calculateKeyPosition = function(object, key) { | |
var props = Object.getOwnPropertyNames(object); | |
// indexOf uses strong comparing (===) and props are always string values | |
key = typeof(key) === typeof("") ? key : key.toString(); | |
return props.indexOf(key); | |
}; | |
var rearrangeKeys = function(object, startIndexPosition) { | |
var props = Object.getOwnPropertyNames(object); | |
for (var i = startIndexPosition; i < props.length; i++) { | |
var currentKey = parseInt(props[i]); | |
var nextKey = currentKey - 1; | |
var value = object[currentKey]; | |
delete object[currentKey]; | |
object[nextKey] = value; | |
} | |
}; | |
var key = 1; | |
var position = calculateKeyPosition(object, key); | |
if (position !== -1) { | |
delete object[key]; | |
rearrangeKeys(object, position); | |
} | |
console.log(object); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment