我有一个对象数组
[{
"data": [{
"name": "John",
"id": 1,
"total": 5
}, {
"name": "Bob",
"id": 2,
"total": 7
}],
"location": "CA"
}, {
"data": [{
"name": "John",
"id": 1,
"total": 1
}, {
"name": "Matt",
"id": 3,
"total": 9
}],
"location": "NY"
}]
我正在尝试通过将lodash或javascript中的键“ id”配对来计算“ total”值的总和来对它进行排序。将此数据提供给堆叠列的高位图表。我通过应用groupBy,sortBy进行了尝试,我看到的所有示例仅使用数组,而不使用数组。
我期望它是结果数组
[{
"data": [{
"name": "Bob",
"id": 2,
"total": 7
},{
"name": "John",
"id": 1,
"total": 5
}],
"location": "CA"
}, {
"data": [{
"name": "Matt",
"id": 3,
"total": 9
},{
"name": "John",
"id": 1,
"total": 1
}, ],
"location": "NY"
}]
答案 0 :(得分:-2)
解决此问题的一种方法是使用香草Javascript:
const arr = [{
"data": [{
"name": "John",
"id": 1,
"total": 5
}, {
"name": "Bob",
"id": 2,
"total": 7
}],
"location": "CA"
}, {
"data": [{
"name": "John",
"id": 1,
"total": 1
}, {
"name": "Matt",
"id": 3,
"total": 9
}],
"location": "NY"
}];
arr.forEach(obj => {
obj.data.sort((a,b) => b.total + b.id - a.total - a.id);
});
console.log(arr);