在对象数组中添加位置/顺序



我有一系列对象如下:

    [{
    "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
       }]
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)

sort对数组进行排序,然后在每个对象上添加prop,相对于用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)

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);

最新更新