How to change the order of the fields in JSON
json, node.js
Solution
May be you could change this 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 to 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 the key order you want in an array and supply to the function. then parse the result back to json. here is a sample fiddle.
Problem
Scenario: Consider I have a JSON documents as follows: ``` { "name": "David", "age" : 78, "NoOfVisits" : 4 } ``` Issues: I wanted to change the sequence/order of the fields in the document, say I want `age`, `NoOfVisits` & then lastly `name`. As of now I am storing the value in temporary variable, deleting the field & recreating the same field. Since the reassignment did not work :( I did it 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 that I will get the desired ordered JSON document. This requirement is peculiar kind but still I want some efficient solution Question: Can someone help out with efficient way to achieve the same?