【发布时间】:2018-05-13 09:12:01
【问题描述】:
你好 Stack Overflow 社区!
我有以下测试数组:
let test = [{
"searchQuery": "test",
"resultsLoaded": -1,
"offset": -1,
"allResults": 10
}, {
"metaData": {
"type": "page-content",
"image": true,
"name": "lorem-ipsum",
"rank": 10,
"tags": ["website:lorem/ipsum"]
},
"componentData": {
"header": "Lorem Ipsum",
"path": "/content/asdf",
"breadcrumbDouble": {
"breadcrumbItem1": {
"href": "lorem ipsum",
"text": "lorem ipsum"
},
"breadcrumbItem2": {
"href": "/content/asdf",
"text": "Lorem Ipsum"
}
},
"content": {
"subheadline": "Lorem Ipsum",
"img": {
"alt": "",
"imgSrc": "/content/dam/production/images/asdf.jpeg.imgTransformer/listPageItem/desktop/1511962617778/asdf.jpg"
},
"tags": [{
"category": "lorem",
"value": "ipsum"
}]
}
}
}, {
"metaData": {
"type": "page-content",
"image": true,
"name": "lorem-ipsum",
"rank": 50,
"tags": ["website:lorem/ipsum"]
},
"componentData": {
"header": "Lorem Ipsum",
"path": "/content/asdf",
"breadcrumbDouble": {
"breadcrumbItem1": {
"href": "lorem ipsum",
"text": "lorem ipsum"
},
"breadcrumbItem2": {
"href": "/content/asdf",
"text": "Lorem Ipsum"
}
},
"content": {
"subheadline": "Lorem Ipsum",
"img": {
"alt": "",
"imgSrc": "/content/dam/production/images/asdf.jpeg.imgTransformer/listPageItem/desktop/1511962617778/asdf.jpg"
},
"tags": [{
"category": "lorem",
"value": "ipsum"
}]
}
}
}, {
"metaData": {
"type": "page-content",
"image": true,
"name": "lorem-ipsum",
"rank": 30,
"tags": ["website:lorem/ipsum"]
},
"componentData": {
"header": "Lorem Ipsum",
"path": "/content/asdf",
"breadcrumbDouble": {
"breadcrumbItem1": {
"href": "lorem ipsum",
"text": "lorem ipsum"
},
"breadcrumbItem2": {
"href": "/content/asdf",
"text": "Lorem Ipsum"
}
},
"content": {
"subheadline": "Lorem Ipsum",
"img": {
"alt": "",
"imgSrc": "/content/dam/production/images/asdf.jpeg.imgTransformer/listPageItem/desktop/1511962617778/asdf.jpg"
},
"tags": [{
"category": "lorem",
"value": "ipsum"
}]
}
}
}];
我现在想要实现的是按metaData.rank从高到低对对象进行排序。
我想像这样使用 lodash 的 orderBy():
let result = orderBy(test, function(e) {
let array = parseInt(e.metaData.rank);
return array;
}, ['desc']);
但我收到以下错误:
TypeError: 无法读取未定义的属性“等级”
console.log(e) 在我的orderBy 函数中向我展示了这个:
{
searchQuery: 'test',
resultsLoaded: -1,
offset: -1,
allResults: 10
}
有解决此问题的快速建议吗?
我知道由于结构不同,第一个对象导致了问题。所以我需要解决它!
【问题讨论】:
-
第一个条目是什么?它应该保持在首位吗?
-
@NinaScholz 在最好的情况下,它应该保持在顶部。
-
@mrks 不同的对象总是在第一位吗?在同一个数组中可以有更多吗?
标签: javascript arrays sorting object lodash