Change order of keys/properties of an object in a function in javascript? -
this question has answer here:
i trying change order of properties or keys of object according definition. find although changes remain within function, reverted outside. wrote simple code show this:
function changeorder(obj) { let keys = object.keys(obj); let reversedobj = new object; (let key = keys.length; key >0; key--) { reversedobj[keys[key-1]] = obj[keys[key - 1]]; } console.log("revered object: "); console.log(reversedobj) obj = reversedobj; console.log("reversing original object: ");console.log(obj) } = { u: { x: 1, y: 2}, v : { x: 3, y: 4} } changeorder(a); console.log("original object outside function: "); console.log(a)
this result get:
revered object: object { v: object, u: object } reversing original object: object { v: object, u: object } original object outside function: object { u: object, v: object }
i verified changes did on property of reversedobj inside function replicated on object outside. why isn't order being maintained?
an object in javascript doesn't guarantee order according ecmascript specification.
however, can convert javascript object stringified json ordered keys.
please go through example:
json.stringify(obj, keysinorder);
here, obj javascript object stringified. keysinorder array containing list of keys included in result, in order.
wiki
Comments
Post a Comment