如何使用第二个数组中对象的相关属性对对象数组进行排序 [英] how to sort an array of objects using a related property from objects in second array

查看:134
本文介绍了如何使用第二个数组中对象的相关属性对对象数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于使用JavaScript进行排序有很多问题,但是我找不到能解决这种情况的任何东西,所以我不认为这是重复的.

There are many questions regarding sorting with JavaScript but I didn't find anything that addresses this case so I don't believe this is a duplicate.

我正在从api获取类似的数据:

I'm getting data like this back from an 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}]

如何按订单数组中对象的sortindex属性对项目数组进行排序?这两个数组中的对象具有公共属性id.是否有一个优雅的lodash/underscore解决方案?

How can I sort the items array by the sortindex property of the objects in the order array? The objects in the two arrays have the common property id. Is there an elegant lodash/underscore solution?

推荐答案

lodash很简单. sortBy函数会将项目移动到sortindex位置,因此我们只需要使用find来获取相应的对象,并返回其sortindex属性以供sortBy使用.

It's straightforward with lodash. The sortBy function will move the items to the sortindex position, so we just need to use find to get the corresponding object, and return its sortindex property for sortBy to use.

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>

这篇关于如何使用第二个数组中对象的相关属性对对象数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆