从JSON对象数组异步查找Avarage

时间:2018-11-05 08:29:40

标签: javascript arrays node.js json asynchronous

我有以下JSON,并且希望找到按deviceId分组的平均压力:

[
    {
        "deviceId": 121,
        "Pressure": 120
    },
    {
        "deviceId": 121,
        "Pressure": 80
    },
    {
        "deviceId": 130,
        "Pressure": 20
    },
    {
        "deviceId": 130,
        "Pressure": 25
    },
    {
        "deviceId": 130,
        "Pressure": 75
    }
]

我想得到

[
    {
        "deviceId" : 121,
        "avg-Pressure": 100
    },
    {
        "deviceId": 130,
        "avg-Pressure": 40
    }
]

如何使用本机方法执行此操作,并且可以异步执行此操作?

4 个答案:

答案 0 :(得分:2)

您可以将数组简化为一个对象,其中键是deviceId,值是带有deviceId和Pressure值数组的对象:

data.reduce(
  (result,{deviceId,Pressure})=>{
    result[deviceId] = result[deviceId] || {deviceId,Pressure:[]};
    result[deviceId].Pressure.push(Pressure);
    return result;    
  },
  {}
)

然后使用Object.values将其再次转换为数组。

然后将数组映射到对象数组,其中Pressure是一个值,因此将每个对象的Pressure值减小为所有压力的总和除以Pressures数组的长度

valuesWithArrayOfPressure.map(
  ({deviceId,Pressure})=>({
    deviceId,
    Pressure:Pressure.reduce((all,item)=>all+item,0)
  })
)

完整代码:

var data = [
    {
        "deviceId": 121,
        "Pressure": 120
    },
    {
        "deviceId": 121,
        "Pressure": 80
    },
    {
        "deviceId": 130,
        "Pressure": 20
    },
    {
        "deviceId": 130,
        "Pressure": 25
    },
    {
        "deviceId": 130,
        "Pressure": 75
    }
];

const valuesWithArrayOfPressure = data.reduce(
  (result, { deviceId, Pressure }) => {
    result[deviceId] = result[deviceId] || {
      deviceId,
      Pressure: [],
    };
    result[deviceId].Pressure.push(Pressure);
    return result;
  },
  {},
);
console.log(
  'object where Pressure is grouped',
  valuesWithArrayOfPressure,
);

console.log(
  'use values and map to get average Pressure values',
  Object.values(valuesWithArrayOfPressure).map(
    ({ deviceId, Pressure }) => ({
      deviceId,
      Pressure: Pressure.reduce(
        (all, item) => all + item,
        0,
      ),
    }),
  ),
);

答案 1 :(得分:1)

我将JSON值存储在arr对象中。

还声明了newArray来存储结果;

我用findAvaragePressurearr调用了newArray来获得想要的结果。

// store the result here
let newArray = [];
const arr = [
    {
        "deviceId": 121,
        "Pressure": 120
    },
    {
        "deviceId": 121,
        "Pressure": 80
    },
    {
        "deviceId": 130,
        "Pressure": 20
    },
    {
        "deviceId": 130,
        "Pressure": 25
    },
    {
        "deviceId": 130,
        "Pressure": 75
    }
];

// check if the object is already token in the new array
const isAvailable = (deviceId, arr) => {
    for (let index=0; index<arr.length; index++) {
        if (arr[index].deviceId == deviceId) {
            return true;
        }
    }
    return false;
}

// for a device id, find the average pressure
const getAvarageValue = (deviceId, arr) => {
    let sum = 0;
    let count = 0;
    for (let index=0; index<arr.length; index++) {
        if (arr[index].deviceId == deviceId) {
            sum += arr[index].Pressure;
            count ++;
        }
    }
    return sum/count;
};

// put the existing array object and new resultent array
const findAvaragePressure = (arr, newArray) => {
    for (let index=0; index<arr.length; index++) {
        if (!isAvailable(arr[index].deviceId, newArray)) {
            const avg_Pressure = getAvarageValue(arr[index].deviceId, arr);
            newArray.push({
                deviceId: arr[index].deviceId,
                avg_Pressure: avg_Pressure
            });
        }
    };
    return newArray
};

const result = findAvaragePressure(arr, newArray);
console.log(result);

答案 2 :(得分:1)

您可以使用array#reducedeviceIdcount上的数据分组。然后使用totalPressure计算每个array#map的平均压力。

deviceId

答案 3 :(得分:0)

类似于其他答案,您可以尝试按deviceId分组,并计算这些组的平均值:

const json = [{
  "deviceId": 121,
  "Pressure": 120
}, {
  "deviceId": 121,
  "Pressure": 80
}, {
  "deviceId": 130,
  "Pressure": 20
}, {
  "deviceId": 130,
  "Pressure": 25
}, {
  "deviceId": 130,
  "Pressure": 75
}]

const deviceGroups = {};
for (const key in json) {
  deviceId = json[key].deviceId;

  if (!deviceGroups[deviceId]) {
    deviceGroups[deviceId] = []
  }

  deviceGroups[deviceId].push(json[key])
}

result = [];
for (const [key, value] of Object.entries(deviceGroups)) {
  const jsonObject = {
    "deviceId": key
  };

  let sum = 0;
  for (const array in deviceGroups[key]) {
    sum += deviceGroups[key][array].Pressure;
  }

  jsonObject["avg-Pressure"] = sum / deviceGroups[key].length;
  result.push(jsonObject);
}

console.log(result);