使用javascript,在格式如下:
[{
"data":{
propertyType: "电量,A相电流,电功率"
},
"odata": {
"prev_0_day_val_diff": "10.189941,-3.0,79.0",
}
},{
"data":{
propertyType: "A相电流,电功率,电量"
},
"odata": {
"prev_0_day_val_diff": "10.189941,-3.0,79.0",
}
}]
如何获取和propertyType中电量所在一样位置的prev_0_day_val_diff中的数字,并求和
首先,我们需要解析这个JSON数组,然后找出"propertyType"中"电量"的位置,然后获取相应位置的"prev_0_day_val_diff"值,最后求和。以下是一个可能的JavaScript解决方案:
let data = [{
"data":{
propertyType: "电量,A相电流,电功率"
},
"odata": {
"prev_0_day_val_diff": "10.189941,-3.0,79.0",
}
},{
"data":{
propertyType: "A相电流,电功率,电量"
},
"odata": {
"prev_0_day_val_diff": "10.189941,-3.0,79.0",
}
}];
let sum = 0;
for(let i = 0; i < data.length; i++) {
let propertyType = data[i].data.propertyType.split(",");
let prev_0_day_val_diff = data[i].odata.prev_0_day_val_diff.split(",");
for(let j = 0; j < propertyType.length; j++) {
if(propertyType[j] === "电量") {
sum += parseFloat(prev_0_day_val_diff[j]);
}
}
}
console.log(sum); // 输出结果
这个脚本将遍历每个对象,然后在"propertyType"中查找"电量"的位置,然后获取相应位置的"prev_0_day_val_diff"值,然后将其解析为浮点数并添加到总和中。最后,它将打印出总和。
const data = [
{
"data": {
propertyType: "电量,A相电流,电功率"
},
"odata": {
"prev_0_day_val_diff": "10.189941,-3.0,79.0"
}
},
{
"data": {
propertyType: "A相电流,电功率,电量"
},
"odata": {
"prev_0_day_val_diff": "10.189941,-3.0,79.0"
}
}
];
function calculateSum(data) {
let sum = 0;
for (let i = 0; i < data.length; i++) {
let propertyType = data[i].data.propertyType.split(",");
let prev_0_day_val_diff = data[i].odata.prev_0_day_val_diff.split(",");
for (let j = 0; j < propertyType.length; j++) {
if (propertyType[j] === "电量") {
sum += parseFloat(prev_0_day_val_diff[j]);
}
}
}
return sum;
}
可以通过调用 calculateSum()
函数来获取结果。
@漏刻有时