JSON.stringify 時のキーの並びを指定する
第二引数に配列を渡す。
(第二引数は関数を渡すと replacer として、置換処理が行われるが、配列の場合は挙動が変わる。ちなみに、第三引数は space で、変換時にインデントされる。)
let o = {
d: 3,
c: 2,
b: 1,
a: 0,
}
let normal = JSON.stringify(o);
console.log(normal); // {'d':3,'c':2,'b':1,'a':0}
let sorted = JSON.stringify(o, ['a', 'b', 'c', 'd', 'e', 'f', 'g']);
console.log(sorted); // {'a':0,'b':1,'c':2,'d':3}
ネストしてたら上から。
let o = {
d: {
f: {
h: 5,
g: 4,
},
e: 3,
},
c:2,
b:1,
a:0,
}
let normal = JSON.stringify(o);
console.log(normal); // {"d":{"f":{"h":5,"g":4},"e":3},"c":2,"b":1,"a":0}
let sorted = JSON.stringify(o, ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']);
console.log(sorted); // {"a":0,"b":1,"c":2,"d":{"e":3,"f":{"g":4,"h":5}}}