sort deep object in javascript

落爺英雄遲暮 提交于 2020-03-05 00:55:53

问题


What is the best way to sort this:

{
    abc: {
        string: 'lorem',
        date: 2
    },
    enc: {
        string: 'ipsum',
        date: 1
    }
}

into this:

[{
    id: 'enc',
    string: 'ipsum',
    date: 1
},
{
    id: 'abc',
    string: 'lorem',
    date: 2
}]

I need an array sorted by the date (Number) with a flat object.


回答1:


First, you need to convert the original object into an array in the format you want:

var arr = [];
for (var key in obj)
  if (obj.hasOwnProperty(key)) {
    var o = obj[key];
    arr.push({ id: key, string: o.string, date: o.date });
  }

Then, you can use the array sort method with a custom comparator for sorting by the date field:

arr.sort(function(obj1, obj2) {
  return obj1.date - obj2.date;
});



回答2:


This will do the trick.

var stuff = {
    abc: {
        string: 'lorem',
        date: 2
    },
    enc: {
        string: 'ipsum',
        date: 1
    }
};

// Put it into an array
var list = [];
for(var i in stuff) {
    if (stuff.hasOwnProperty(i)) {
        list.push(stuff[i]);
    }
}

// sort the array
list.sort(function(a, b) {
    return a.date - b.date;
});

See also:
https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference:Global_Objects:Array:sort




回答3:


I would do it in two steps: First, convert the object to an array:

var array = [],
   o;

for (var key in obj) {
    if (obj.hasOwnProperty(key)) {
        o = obj[key];
        o.id = key;
        array.push(o);
    }
}

Then, sort it like this:

array.sort(function (a, b) {
    a.date - b.date;
});


来源:https://stackoverflow.com/questions/4299116/sort-deep-object-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!