Help us understand the problem. What is going on with this article?

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

More than 3 years have passed since last update.

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}}}
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away