Hi 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:无法读取未定义的属性'rank'
console.log(e)
函数中的 orderBy
向我显示了这个:
{
searchQuery: 'test',
resultsLoaded: -1,
offset: -1,
allResults: 10
}
有任何快速建议来解决这个问题吗?
我知道第一个对象是因为结构不同而引起问题。所以我需要解决它!
答案 0 :(得分:1)
代替e.metaData.rank
使用:
_.get(e, ['metaData', 'rank'], /*value if rank field is not exist*/ -1);