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

Categories

0 votes
355 views
in Technique[技术] by (71.8m points)

node.js - How to change the order of the fields in JSON

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

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

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...