var obj = {
x: 45,
b: {
func: function(){alert('a')},
name: "b"
},
a: "prueba"
};
var nw = moveProp(obj, "a", "x"); //-- move 'a' to position of 'x'
console.log(nw, obj);
//--
function moveProp(obj, moveKey, toKey){
var temp = Object.assign({}, obj)
var tobj;
var resp = {};
tobj = temp[moveKey];
delete temp[moveKey];
for(var prop in temp){
if (prop===toKey) resp[moveKey] = tobj;
resp[prop] = temp[prop];
}
return resp;
}
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter