LoginSignup
2
2

More than 5 years have passed since last update.

JSON.stringify 時のキーの並びを指定する

Posted at

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}}}
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2