sort object properties and JSON.stringify

后端 未结 22 2329
南方客
南方客 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:26

    Works with lodash, nested objects, any value of object attribute:

    function sort(myObj) {
      var sortedObj = {};
      Object.keys(myObj).sort().forEach(key => {
        sortedObj[key] = _.isPlainObject(myObj[key]) ? sort(myObj[key]) : myObj[key]
      })
      return sortedObj;
    }
    JSON.stringify(sort(yourObj), null, 2)
    

    It relies on Chrome's and Node's behaviour that the first key assigned to an object is outputted first by JSON.stringify.

提交回复
热议问题