gpt4 book ai didi

javascript - 如何在 Node.JS 中对对象的数据执行减法?

转载 作者:太空宇宙 更新时间:2023-11-03 22:03:32 24 4
gpt4 key购买 nike

我有审查员的数据。它由当前和上个月的数据组成,作为对象数组。现在我需要找到当前和上个月数据的差异,并将差异分配给上个月的数据对象。

例如,我有以下数据。

deviceData = [
{
"_id": "sb-0001",
"heat": 100,
"humidity": 200,
"time": "This Month"
},
{
"_id": "a-1",
"heat": 60,
"humidity": 40,
"time": "This Month"
},
{
"_id": "a-1",
"heat": 20,
"humidity": 10,
"time": "Last Month"
},
{
"_id": "sb-0001",
"heat": 20,
"humidity": 30,
"time": "Last Month"
}
]

现在我想找到如下所示的差异。

deviceData = [
{
"_id": "sb-0001",
"heat": 100,
"humidity": 200,
"time": "This Month"
},
{
"_id": "a-1",
"heat": 60,
"humidity": 40,
"time": "This Month"
},
{
"_id": "a-1",
"heat": 20,
"humidity": 10,
"time": "Last Month",
"diff_heat":40,
"diff_humidity":30
},
{
"_id": "sb-0001",
"heat": 20,
"humidity": 30,
"time": "Last Month",
"diff_heat":80,
"diff_humidity":170
}
]

我尝试了以下代码来计算差异,但没有得到结果。

let difference;
difference = [templateData.reduce((obj, n) => {
for (var prop in n) {
if (obj.hasOwnProperty(prop) && obj['time']==n['time']) obj[prop] -= n[prop];
else obj[prop] = n[prop];
}
return obj;
}, {})]

还有其他办法吗?

最佳答案

此代码应该执行您希望的操作,我们创建上个月数据的映射,然后循环遍历数组并从当前月份中减去。

我通过循环对象的属性并减去它们(如果它们是数字)来使这个更加通用。

const deviceData = [ { "_id": "sb-0001", "heat": 100, "humidity": 200, "time": "This Month" }, { "_id": "a-1", "heat": 60, "humidity": 40, "time": "This Month" }, { "_id": "a-1", "heat": 20, "humidity": 10, "time": "Last Month" }, { "_id": "sb-0001", "heat": 20, "humidity": 30, "time": "Last Month" } ]; 

let lastMonthData = deviceData.reduce((acc, el) => {
if (el.time === "Last Month") {
acc[el._id] = el;
}
return acc;
}, {});

let result = deviceData.reduce((acc, el) => {
if (el.time === "This Month" && lastMonthData[el._id]) {
Object.entries(el).forEach(([key,val]) => {
if (Number.isFinite(lastMonthData[el._id][key])) {
lastMonthData[el._id][key + "_diff"] = val - lastMonthData[el._id][key];
}
});
}
acc.push(el);
return acc;
}, []);

console.log("Result:", result);

关于javascript - 如何在 Node.JS 中对对象的数据执行减法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60168494/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com