我有以下数据集需要根据" AcctCode"进行排序。和" SuperID"如下使用lodash的预期结果。
任何人都可以帮助我根据" AcctCode"按顺序排序升序。和" SuperID"如下所示,我已经提到了预期的结果集。我使用了_.orderBy(data),但如果我们传递一个对象的整个数组而不是我在下面提到的那样,它会给出一个答案。
示例数据集:
[
{
"100" : [
{
"id" : 1,
"EmpId" : 100,
"AcctCode" : "2002-00",
"SuperID" : 2000,
"ReportNo" : "10000"
},
{
"id" : 2,
"EmpId" : 100,
"AcctCode" : "2001-00",
"SuperID" : 2000,
"ReportNo" : "10000"
},
{
"id" : 3,
"EmpId" : 100,
"AcctCode" : "2000-00",
"SuperID" : 2000,
"ReportNo" : "10000"
}
],
"101" : [
{
"id" : 4,
"EmpId" : 101,
"AcctCode" : "2001-00",
"SuperID" : 2000,
"ReportNo" : "10000"
},{
"id" : 3,
"EmpId" : 100,
"AcctCode" : "2001-10",
"SuperID" : 2000,
"ReportNo" : "10000"
}
]
}]
预期结果如下
[
{
"100" : [
{
"id" : 3,
"EmpId" : 100,
"AcctCode" : "2000-00",
"SuperID" : 2000,
"ReportNo" : "10000"
},
{
"id" : 2,
"EmpId" : 100,
"AcctCode" : "2001-00",
"SuperID" : 2000,
"ReportNo" : "10000"
},
{
"id" : 1,
"EmpId" : 100,
"AcctCode" : "2002-00",
"SuperID" : 2000,
"ReportNo" : "10000"
},
],
"101" : [
{
"id" : 4,
"EmpId" : 101,
"AcctCode" : "2001-00",
"SuperID" : 2000,
"ReportNo" : "10000"
},{
"id" : 3,
"EmpId" : 100,
"AcctCode" : "2001-10",
"SuperID" : 2000,
"ReportNo" : "10000"
}
]
}]
答案 0 :(得分:1)
使用lodash
:
var data = ... //per your definition
// reduce over the key/value pairs (k,v) to produce a copy of the
// object but with values sorted as you described
var obj = _.reduce(data[0],(acc,v, k) => {
acc[k] = _.sortBy(v, ['AcctCode','SuperID']);
return acc;
},{});
[obj] // to re-wrap the object into array so we get the output format you specified
答案 1 :(得分:1)
您需要使用mapValues映射data[0]
的值,然后使用orderby:
const result = _.mapValues(data[0], items =>
_.orderBy(items, ['AcctCode', 'SuperID'], ['asc', 'desc'] ))
目前尚不清楚SuperID
的排序顺序是什么,所以我只是将其设置为降序。
答案 2 :(得分:0)
没有lodash
使用sort
方法:
Object.values(arr[0]).sort((a, b) => {
var aAcctCode = parseInt(a.AcctCode.split('-').join(''));
var bAcctCode = parseInt(b.AcctCode.split('-').join(''));
var aSuperID = parseInt(a.SuperID);
var bSuperID = parseInt(b.SuperID);
return aAcctCode - bAcctCode != 0 ? aAcctCode - bAcctCode : aSuperID - bSuperID;
});
sort
算法在到位后,您的同一个arr将保存已排序的值。