I\'m trying to find a way to move an object element to a specific position.
For example, I\'ve this object :
{
\"element1\" : {} // object,
\"el
Here's my code for doing that logic. Thanks!
function _moveElementObject(object, from, to) {
var newObjects = [];
var newObject = {};
var oldObject = {};
var firstObject = {};
var lastObject = {};
var toMoveKey = "";
var toMoveValue;
oldObject = object;
var objLength = _countProperties(oldObject);
var keyNo = 1;
for (var key in oldObject) {
if (keyNo == from) {
toMoveKey = key;
toMoveValue = oldObject[key];
}
keyNo++;
}
console.log(oldObject);
keyNo = 1;
for (var key in oldObject) {
if (keyNo < to) {
firstObject[key] = oldObject[key];
newObject[key] = firstObject[key];
}
keyNo++;
}
console.log(firstObject);
keyNo = 1;
for (var key in oldObject) {
if (to <= objLength) {
lastObject[key] = oldObject[key];
}
keyNo++;
}
delete lastObject[toMoveKey];
newObject[toMoveKey] = toMoveValue;
for (var key in lastObject) {
newObject[key] = lastObject[key];
}
console.log(newObject);
console.log("push");
return newObject;
}
var sampleObj = {
"element1" : {} // object,
"element2" : {},
"element3" : {}
};
_moveElementObject(sampleObj,3,1);
// output object,
{
"element3" : {},
"element1" : {},
"element2" : {},
}