如何对一个具有多个参数的对象数组进行数字排序

时间:2019-06-27 14:03:00

标签: javascript html

我需要在Web应用程序中创建一个函数。该函数接收一个JS对象作为参数,并从最低到最高返回有组织的列表。该对象具有两个要分析的参数。

var medicines = [
  {type:"Glibenclamida 5 mg", hour1:2, hour2: 4},
  {type:"Noretisterona 0,35 mg", hour1:4, hour2: 8},
  {type:"Glibenclamida 99 mg", hour1:8, hour2: 16}
];

所以,这只是一个例子,我需要这些列表返回...

1: hour 2- Glibenclamida 5 mg
2: hour 4- Glibenclamida 5 mg, Noretisterona 0,35 mg
3: hour 8- Noretisterona 0,35 mg, Glibenclamida 99 mg
4: hour 16 - Glibenclamida 99 mg

这只是一个例子,我需要像这样的组织列表。

3 个答案:

答案 0 :(得分:1)

这可以使用reduce来解决,请看下面的解决方案。

var medicines = [
  {type:"Glibenclamida 5 mg", hour1:2, hour2: 4},
  {type:"Noretisterona 0,35 mg", hour1:4, hour2: 8},
  {type:"Glibenclamida 99 mg", hour1:8, hour2: 16}
];

var convertedMedicines = medicines.reduce((res, medicine) => {
  res[medicine.hour1] = res[medicine.hour1] || [];
  res[medicine.hour2] = res[medicine.hour2] || [];
  res[medicine.hour1].push(medicine.type);
  res[medicine.hour2].push(medicine.type);
  return res;
}, {});

console.log(convertedMedicines)

答案 1 :(得分:0)

这也可以通过地图功能来完成。映射对象数组,然后检查类型索引是否存在。如果确实存在,那么我们将其正常推送;如果它不存在,则将其与先前的值(iln -1)一起推送。

var medicines = [{
    type: "Glibenclamida 5 mg",
    hour1: 2,
    hour2: 4
  },
  {
    type: "Noretisterona 0,35 mg",
    hour1: 4,
    hour2: 8
  },
  {
    type: "Glibenclamida 99 mg",
    hour1: 8,
    hour2: 16
  }
];

let an = medicines.map((val, iln) => {
  if (!iln && medicines[iln + 1].type) {
    return {
      [iln + 1]: "hour" + val.hour1 + "-" + val.type
    }
  } else {
    return {
      [iln + 1]: "hour" + medicines[iln].hour1 + "-" + medicines[iln - 1].type + "," + medicines[iln].type
    }
  }
})

an.push({[medicines.length + 1]:  "hour" + medicines[medicines.length-1].hour2 + "-" + medicines[medicines.length-1].type})
console.log(JSON.stringify(an))

我们手动推送最后一个值,因为它没有后继,并且在map内执行将是无用的。

您得到的输出为

[{
  "1": "hour2-Glibenclamida 5 mg"
}, {
  "2": "hour4-Glibenclamida 5 mg,Noretisterona 0,35 mg"
}, {
  "3": "hour8-Noretisterona 0,35 mg,Glibenclamida 99 mg"
}, {
  "4": "hour16-Glibenclamida 99 mg"
}]

答案 2 :(得分:0)

Marius' reduce上的改进

这不会硬编码hour1和hour2-如果会有一个hour3等-因此将使用以hour开头的任何键

var medicines = [
  {type:"Glibenclamida 5 mg",    hour1: 2, hour2: 4},
  {type:"Noretisterona 0,35 mg", hour1: 4, hour2: 8, hour3: 16},
  {type:"Glibenclamida 99 mg",   hour1: 8, hour2: 16}
];

var convertedMedicines = medicines.reduce((res, medicine) => {
  Object.keys(medicine).forEach(key => {
    if (key.indexOf("hour")==0) {
      res["hour "+medicine[key]] = res["hour "+medicine[key]] || [];
      res["hour "+medicine[key]].push(medicine.type);
   }
  });
  return res;
}, {});

console.log(convertedMedicines)