Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
371 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...