我想根据数组对下面的 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 进行排序?
最佳答案
你不能对 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);
关于javascript - 根据自定义排序顺序数组对 JSON 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42520651/