我有一个对象数组,如下所示:
[{
"id": 1,
"Size": 90,
"Maturity": 24,
},
{
"id": 2,
"Size": 85,
"Maturity": 22,
},
{
"id": 3,
"Size": 80,
"Maturity": 20,
}]我需要在这个数组的基础上不同的属性值排序(例如:成熟度),并添加一个具有升序/排名的列顺序。例如:
[{
"id": 1,
"Size": 90,
"Maturity": 22,
"Order": 2
},
{
"id": 2,
"Size": 85,
"Maturity": 25,
"Order": 3
},
{
"id": 3,
"Size": 80,
"Maturity": 20,
"Order": 1
}]发布于 2019-03-13 20:56:40
const arr = [{
"id": 1,
"Size": 90,
"Maturity": 24,
},
{
"id": 2,
"Size": 85,
"Maturity": 22,
},
{
"id": 3,
"Size": 80,
"Maturity": 20,
}];
arr
.map((item,index) => ({ ...item, Order: index + 1 }))
.sort((a, b) => b.Maturity - a.Maturity)发布于 2019-03-13 21:01:09
使用sort对数组进行排序,然后根据使用forEach对其进行排序的索引为每个对象添加属性
var inp = [{
id: 1,
Size: 90,
Maturity: 24,
},
{
id: 2,
Size: 85,
Maturity: 22,
},
{
id: 3,
Size: 80,
Maturity: 20,
}]
// Sort
inp.sort(function(a, b){
return a.Maturity == b.Maturity ? 0 : +(a.Maturity > b.Maturity) || -1;
});
// add prop
inp.forEach(function(row, index) {
row.index = index + 1;
});
console.log(inp)
发布于 2019-03-13 21:02:54
var objs = [
{
"id": 1,
"Size": 90,
"Maturity": 24,
},
{
"id": 2,
"Size": 85,
"Maturity": 22,
},
{
"id": 3,
"Size": 80,
"Maturity": 20,
}];
function compare(a,b) {
if (a.Size < b.Size)
return -1;
if (a.Size > b.Size)
return 1;
return 0;
}
objs.sort(compare);
for (var i = 0; i < objs.length; i++) {
objs[i].Order = i+1;
}
console.log(objs);https://stackoverflow.com/questions/55142119
复制相似问题