sort object properties and JSON.stringify

后端 未结 22 2330
南方客
南方客 2020-11-28 05:44

My application has a large array of objects, which I stringify and save them to the disk. Unfortunately, when the objects in the array are manipulated, and sometimes replac

22条回答
  •  伪装坚强ぢ
    2020-11-28 06:21

    After all, it needs an Array that caches all keys in the nested object (otherwise it will omit the uncached keys.) The oldest answer is just plain wrong, because second argument doesn't care about dot-notation. So, the answer (using Set) becomes.

    function stableStringify (obj) {
      const keys = new Set()
      const getAndSortKeys = (a) => {
        if (a) {
          if (typeof a === 'object' && a.toString() === '[object Object]') {
            Object.keys(a).map((k) => {
              keys.add(k)
              getAndSortKeys(a[k])
            })
          } else if (Array.isArray(a)) {
            a.map((el) => getAndSortKeys(el))
          }
        }
      }
      getAndSortKeys(obj)
      return JSON.stringify(obj, Array.from(keys).sort())
    }
    

提交回复
热议问题