Javascript: Change object property position
Tue Nov 21 2023 18:30:57 GMT+0000 (Coordinated Universal Time)
Saved by
@marcopinero
#javascript
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;
}
content_copyCOPY
Comments