排序对象属性和JSON.stringify [英] sort object properties and JSON.stringify

查看:731
本文介绍了排序对象属性和JSON.stringify的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序有大量对象,我将其字符串化并保存到磁盘。遗憾的是,当数组中的对象被操纵并且有时被替换时,对象上的属性以不同的顺序(它们的创建顺序?)列出。当我在数组上执行JSON.stringify()并保存它时,diff会显示以不同顺序列出的属性,这在尝试使用diff和合并工具进一步合并数据时很烦人。

My application has a large array of objects, which I stringify and save to disk. Unfortuately, when the objects in the array are manipulated, and sometimes replaced, the properties on the objects are listed in different orders (their creation order?). When I do JSON.stringify() on the array and save it, a diff shows the properties getting listed in different orders, which is annoying when trying to merge the data further with diff and merging tools.

理想情况下,我想在执行stringify之前按字母顺序对对象的属性进行排序,或者作为stringify操作的一部分。存在用于在许多地方操纵数组对象的代码,并且改变它们以总是以显式顺序创建属性将是困难的。

Ideally I would like to sort the properties of the objects in alphabetical order prior to performing the stringify, or as part of the stringify operation. There is code for manipulating the array objects in many places, and altering these to always create properties in an explicit order would be difficult.

非常欢迎建议!

简明示例:

obj = {}; obj.name="X"; obj.os="linux";
JSON.stringify(obj);
obj = {}; obj.os="linux"; obj.name="X";
JSON.stringify(obj);

这两个stringify调用的输出是不同的,并且显示在我的数据差异中,但是我的应用程序不关心属性的排序..对象是以多种方式构建的。

The output of these two stringify calls is different, and showing up in a diff of my data, but my application doesn't care about the ordering of properties.. the objects are constructed in many ways and places..

推荐答案

更简单,现代和当前浏览器支持的方法就是这样:

The simpler, modern and currently browser supported approach is simply this:

JSON.stringify(sortMyObj, Object.keys(sortMyObj).sort());

但是,此方法会删除未引用的任何嵌套对象,并且不会应用于其中的对象阵列。如果你想要这样的输出,你也想要展平排序对象:

However, this method does remove any nested objects that aren't referenced and does not apply to objects within arrays. You will want to flatten the sorting object as well if you want something like this output:

{"a":{"h":4,"z":3},"b":2,"c":1}

你可以这样做:

var flattenObject = function(ob) {
    var toReturn = {};

    for (var i in ob) {
        if (!ob.hasOwnProperty(i)) continue;

        if ((typeof ob[i]) == 'object') {
            var flatObject = flattenObject(ob[i]);
            for (var x in flatObject) {
                if (!flatObject.hasOwnProperty(x)) continue;

                toReturn[i + '.' + x] = flatObject[x];
            }
        } else {
            toReturn[i] = ob[i];
        }
    }
    return toReturn;
};

JSON.stringify(sortMyObj, Object.keys(flattenObject(sortMyObj)).sort());

要以编程方式使用您可以自行调整的内容,您需要将对象属性名称推送到数组,然后按字母顺序对数组进行排序并遍历该数组(将按正确的顺序),并按该顺序从对象中选择每个值。还检查hasOwnProperty,因此您肯定只拥有对象自己的属性。以下是一个例子:

To do it programmatically with something you can tweak yourself, you need to push the object property names into an array, then sort the array alphabetically and iterate through that array (which will be in the right order) and select each value from the object in that order. "hasOwnProperty" is checked also so you definitely have only the object's own properties. Here's an example:

var obj = {"a":1,"b":2,"c":3};

function iterateObjectAlphabetically(obj, callback) {
    var arr = [],
        i;

    for (i in obj) {
        if (obj.hasOwnProperty(i)) {
            arr.push(i);
        }
    }

    arr.sort();

    for (i = 0; i < arr.length; i++) {
        var key = obj[arr[i]];
        //console.log( obj[arr[i]] ); //here is the sorted value
        //do what you want with the object property
        if (callback) {
            // callback returns arguments for value, key and original object
            callback(obj[arr[i]], arr[i], obj);
        }
    }
}

iterateObjectAlphabetically(obj, function(val, key, obj) {
    //do something here
});

同样,这应该保证您按字母顺序迭代。

Again, this should guarantee that you iterate through in alphabetical order.

最后,以最简单的方式进一步研究,这个库将递归地允许您对传递给它的任何JSON进行排序: https://www.npmjs.com/package/json-stable-stringify

Finally, taking it further for the simplest way, this library will recursively allow you to sort any JSON you pass into it: https://www.npmjs.com/package/json-stable-stringify

var stringify = require('json-stable-stringify');
var obj = { c: 8, b: [{z:6,y:5,x:4},7], a: 3 };
console.log(stringify(obj));

输出

{"a":3,"b":[{"x":4,"y":5,"z":6},7],"c":8}

这篇关于排序对象属性和JSON.stringify的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆