基于自定义排序顺序数组对JSON进行排序

时间:2017-02-28 23:30:54

标签: javascript json sorting

我想根据数组对下面的json响应进行排序。

{
    "expanded": {
        "developer": {
            "numFound": 1,
            "start": 0,
            "maxScore": 0.13050619,
            "docs": [
                {
                    "title": "developer"
                }
            ]
        },
        "shop": {
            "numFound": 1,
            "start": 0,
            "maxScore": 1.1272022,
            "docs": [
                {
                    "title": "shop"
                }
            ]
        },
        "support": {
            "numFound": 84,
            "start": 0,
            "maxScore": 1.3669837,
            "docs": [
                {
                    "title": "support"
                }
            ]
        }
    }
}

我想基于以下排序数组进行排序(与下面的顺序相同)。

[ 'shop', 'support', 'developer']

有没有办法根据一些自定义值对这个json进行排序?

2 个答案:

答案 0 :(得分:3)

您无法对json进行排序,但您可以创建一个对象数组并对其进行排序:

let foo = {"expanded": {"developer": {"numFound": 1,"start": 0,"maxScore": 0.13050619,"docs": [{"title": "developer"}]},"shop": {"numFound": 1,"start": 0,"maxScore": 1.1272022,"docs": [{"title": "shop"}]},"support": {"numFound": 84,"start": 0,"maxScore": 1.3669837,"docs": [{"title": "support"}]}}};

let orderArr = ['shop', 'support', 'developer'];

let res = Object.keys(foo.expanded)
    .map(a => ({[a] : foo.expanded[a]}))
    .sort((a,b) => (orderArr.indexOf(Object.keys(a)[0]) + 1) - (orderArr.indexOf(Object.keys(b)[0]) + 1));

console.log(res);

答案 1 :(得分:1)

似乎没有必要排序,因为明确定义了属性的顺序。相反,只需将所需对象放入数组中:

let ordered = ['shop', 'support', 'developer'].map(property => {
  return {[property]: foo.expanded[property]};
});