最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

arrays - sort deep object in javascript - Stack Overflow

programmeradmin1浏览0评论

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.

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.

Share Improve this question asked Nov 28, 2010 at 21:15 David HellsingDavid Hellsing 109k44 gold badges180 silver badges214 bronze badges 1
  • Probably by extracting the dates into a sortable object, such an array, sort that and append the objects according to the sort. – Anders Commented Nov 28, 2010 at 21:20
Add a ment  | 

4 Answers 4

Reset to default 7

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 parator for sorting by the date field:

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

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/en/Core_JavaScript_1.5_Reference:Global_Objects:Array:sort

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;
});

Here's my quick one-liner for this:

let new = Object.entries(obj).map((n) => ({ id: n[0], ...n[1] })).sort(({ date: a }, { date: b }) => a - b)

Let's break it down:

let new = Object.entries(obj);                        // convert object to [ key, value ] array
new = new.map((n) => ({ id: n[0], ...n[1] }) );       // map array to [ { id: key, ...value } ]
new = new.sort(({ date: a }, { date: b }) => a - b);  // sort by date
发布评论

评论列表(0)

  1. 暂无评论