关于使用 JavaScript 排序有很多问题,但我没有找到任何可以解决此问题的内容,因此我不认为这是重复的。
我从 api 获取这样的数据:
//items array
var items = [{id:1, name:'bill'}, {id:2, name:'sam'}, {id:3, name: mary}, {id:4, name:'jane'}]
//sort order array
var order = [{id:1, sortindex:4}, {id:2, sortindex:2}, {id:3, sortindex: 1}, {id:4, sortindex:3}]
如何通过 order 数组中对象的 sortindex
属性对 items 数组进行排序?两个数组中的对象具有共同的属性id
。有优雅的 lodash/下划线解决方案吗?
最佳答案
lodash 的使用非常简单。 sortBy
函数会将项目移动到 sortindex
位置,因此我们只需要使用 find
来获取相应的对象,并返回其sortindex
属性供 sortBy
使用。
var items = [{id:1, name:'bill'}, {id:2, name:'sam'}, {id:3, name: 'mary'}, {id:4, name:'jane'}];
var order = [{id:1, sortindex:4}, {id:2, sortindex:2}, {id:3, sortindex: 1}, {id:4, sortindex:3}];
var sorted = _.sortBy(items, function(item) {
// sorts by the value returned here
return _.find(order, function(ordItem) {
// find the object where the id's match
return item.id === ordItem.id;
}).sortindex; // that object's sortindex property is returned
});
document.body.textContent = JSON.stringify(sorted);
<script src="https://rawgit.com/lodash/lodash/3.0.1/lodash.min.js"></script>
关于javascript - 如何使用第二个数组中对象的相关属性对对象数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28867721/