node.js - How to change the order of the fields in JSON -
scenario: consider have json documents follows:
{ "name": "david", "age" : 78, "noofvisits" : 4 }
issues: wanted change sequence/order of fields in document, want age
, noofvisits
& lastly name
.
as of storing value in temporary variable, deleting field & recreating same field. since reassignment did not work :(
i did in following way:
temp = doc["age"]; delete doc['age']; doc["age"] = temp; temp = doc["noofvisits "]; delete doc['noofvisits ']; doc["noofvisits"] = temp; temp = doc["name"]; delete doc['name']; doc["name"] = temp;
so desired ordered json document. requirement peculiar kind still want efficient solution
question: can out efficient way achieve same?
may change using json.stringify()
do like
var json = { "name": "david", "age" : 78, "noofvisits" : 4 }; console.log(json); //outputs - object {name: "david", age: 78, noofvisits: 4} //change order noofvisits,age,name var k = json.parse(json.stringify( json, ["noofvisits","age","name"] , 4)); console.log(k); //outputs - object {noofvisits: 4, age: 78, name: "david"}
put key order want in array , supply function. parse result json. here sample fiddle.
Comments
Post a Comment