Поиск Avarage из массива объектов JSON асинхронно - PullRequest
0 голосов
/ 05 ноября 2018

У меня есть следующий 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 голосов
/ 05 ноября 2018

Вы можете использовать array#reduce для группировки ваших данных по deviceId вместе с count и totalPressure. Затем с помощью array#map рассчитайте среднее давление для каждого deviceId.

const data = [ { "deviceId": 121, "Pressure": 120 }, { "deviceId": 121, "Pressure": 80 }, { "deviceId": 130, "Pressure": 20 }, { "deviceId": 130, "Pressure": 25 }, { "deviceId": 130, "Pressure": 75 } ],
      result = Object.values(data.reduce((r, {deviceId, Pressure}) => {
        r[deviceId] = r[deviceId] || {deviceId, totalPressure : 0, count : 0};
        r[deviceId].totalPressure += Pressure;
        r[deviceId].count += 1;
        return r;
      }, {}))
      .map(({deviceId, totalPressure, count}) => ({deviceId, 'avg-Pressure' : totalPressure/count}));
      
console.log(result);
0 голосов
/ 05 ноября 2018

Вы можете уменьшить ваш массив до объекта, где ключом является deviceId, а значением является объект с deviceId и массивом значений Pressure:

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

Затем используйте Object.values, чтобы снова превратить его в массив.

Затем сопоставьте массив с массивом объектов, где Pressure - одно значение, поэтому уменьшите значения Давления каждого объекта до суммы всех давлений, деленной на длину массива Давлений

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,
      ),
    }),
  ),
);
0 голосов
/ 05 ноября 2018

Подобно другим ответам, вы можете попробовать сгруппировать по 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);
0 голосов
/ 05 ноября 2018

Я храню значения JSON в arr объекте.

Также объявлено newArray для хранения результатов;

Я вызвал findAvaragePressure с помощью arr и 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);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...