对象列表,有关如何组织它们的建议

时间:2019-06-18 03:58:48

标签: javascript arrays object grouping

我有一个类似于以下示例的对象列表:

[
  {time: 68, value: 300, metric: "tubingPressure"},
  {time: 69, value: 300, metric: "tubingPressure"},
  {time: 70, value: 361.81, metric: "tubingPressure"},
  {time: 68, value: 137.62, metric: "oilTemp"},
  {time: 69, value: 133.41, metric: "oilTemp"},
  {time: 70, value: 126.68, metric: "oilTemp"},
  {time: 68, value: 172.22, metric: "flareTemp"},
  {time: 69, value: 147.03, metric: "flareTemp"},
  {time: 70, value: 173.11, metric: "flareTemp"}
]

基本上,其值为“ tubingPressure”,“ oilTemp”和“ flareTemp” 在68年代,69年代和70年代

我需要根据时间将它们排序在一起,所以看起来像这样,

data = [ { time:68, tubingpressure: 300, oilTemp: 137.62, flareTemp: 172.22 }, { time:69, tubingpressure: 300, oilTemp: 133.41, flareTemp: 147.03 }, { time:70, tubingpressure: 361.81, oilTemp: 126.68, flareTemp: 173.11 } ]

如果我们拥有更大的数据集(例如,时间从68到5000),有什么更好的方法来解决此问题?

我尝试反复遍历该列表以将它们分组,但是我不确定这是否是一种性能好的方法。

3 个答案:

答案 0 :(得分:0)

var obj = [
  {time: 68, value: 300, metric: "tubingPressure"},
  {time: 69, value: 300, metric: "tubingPressure"},
  {time: 70, value: 361.81, metric: "tubingPressure"},
  {time: 68, value: 137.62, metric: "oilTemp"},
  {time: 69, value: 133.41, metric: "oilTemp"},
  {time: 70, value: 126.68, metric: "oilTemp"},
  {time: 68, value: 172.22, metric: "flareTemp"},
  {time: 69, value: 147.03, metric: "flareTemp"},
  {time: 70, value: 173.11, metric: "flareTemp"}
];

const groupBy = key => array =>
  array.reduce((objectsByKeyValue, obj) => {
    const value = obj[key];
    objectsByKeyValue[value] = (objectsByKeyValue[value] || []).concat(obj);
    return objectsByKeyValue;
  }, {});
  
  
  const groupByTime = groupBy('time');
  
  
  console.log(
  JSON.stringify({
    objTime: groupByTime(obj)
  }, null, 1)
);
  
  

答案 1 :(得分:0)

使用sort对对象进行排序,sort会根据您的条件进行回调。

  

arr.sort([compareFunction])

var obj = [
  {time: 68, value: 300, metric: "tubingPressure"},
  {time: 69, value: 300, metric: "tubingPressure"},
  {time: 70, value: 361.81, metric: "tubingPressure"},
  {time: 68, value: 137.62, metric: "oilTemp"},
  {time: 69, value: 133.41, metric: "oilTemp"},
  {time: 70, value: 126.68, metric: "oilTemp"},
  {time: 68, value: 172.22, metric: "flareTemp"},
  {time: 69, value: 147.03, metric: "flareTemp"},
  {time: 70, value: 173.11, metric: "flareTemp"}
];


console.log(obj.sort((a, b) => a.time - b.time))

答案 2 :(得分:0)

arr1.forEach((obj) => {
    let object = newArr1.find(prevObj => prevObj.time === obj.time)
    let {metric,value,time} = obj;
    if(object){
        object[metric] = value;
    } else{
        let objectToPush = {
            time: time
        };
        objectToPush[metric] = value;
        newArr1.push(objectToPush)
    }
});