我有一个数组
Result = [{"01": 330,"02": 353,"03": 178,"04": 353,"KID": 10,"PID": 5},
{"01": 320,"02": 112,"03": 328,"04": 123,"KID": 11,"PID": 6},
{"01": 110,"02": 253,"03": 375,"04": 233,"KID": 12,"PID": 7}]
我知道如何对所有键求和,如下所示:
Result.forEach(item =>{
let sum = Object.keys(item).reduce((acc,value) => acc + item[value],0);
item["total"] = sum;
})
如何找到不包含"KID"
和"PID"
键的值的总和?
答案 0 :(得分:5)
您可以过滤键。
var result = [{ "01": 330, "02": 353, "03": 178, "04": 353, "KID": 10, "PID": 5 }, { "01": 320, "02": 112, "03": 328, "04": 123, "KID": 11, "PID": 6 }, { "01": 110, "02": 253, "03": 375,"04": 233, "KID": 12, "PID": 7 }];
result.forEach(item => item.total = Object
.keys(item)
.filter(k => k !== 'KID' && k !== 'PID')
.reduce((s, k) => s + item[k], 0)
);
console.log(result);
或者您可以预先取得密钥,并仅与所需密钥相加。
var result = [{ "01": 330, "02": 353, "03": 178, "04": 353, "KID": 10, "PID": 5 }, { "01": 320, "02": 112, "03": 328, "04": 123, "KID": 11, "PID": 6 }, { "01": 110, "02": 253, "03": 375,"04": 233, "KID": 12, "PID": 7 }],
exclude = ['KID', 'PID'],
keys = Object.keys(result[0]).filter(k => !exclude.includes(k));
result.forEach(item => item.total = keys.reduce((s, k) => s + item[k], 0));
console.log(result);
答案 1 :(得分:2)
这是您的方法。
Result = [{"01": 330,"02": 353,"03": 178,"04": 353,"KID": 10,"PID": 5},
{"01": 320,"02": 112,"03": 328,"04": 123,"KID": 11,"PID": 6},
{"01": 110,"02": 253,"03": 375,"04": 233,"KID": 12,"PID": 7}]
// Execlude someKeys, if they are available in the array then they will be execluded.
var execludedKeys = ["PID", "KID"];
Result.forEach(item =>{
let sum = Object.keys(item).reduce((acc,value) =>
execludedKeys.indexOf(value) == -1 ? (acc + item[value]) : acc
,0);
item["total"] = sum;
});
console.log(Result)
答案 2 :(得分:1)
您可以改用Object.entries
,然后进行if
检查。
const data = [{"01": 330,"02": 353,"03": 178,"04": 353,"KID": 10,"PID": 5}, {"01": 320,"02": 112,"03": 328,"04": 123,"KID": 11,"PID": 6}, {"01": 110,"02": 253,"03": 375,"04": 233,"KID": 12,"PID": 7}]
data.forEach(obj => {
obj.total = Object.entries(obj)
.reduce((r, [k, v]) => {
if (k != 'KID' && k != 'PID') r += obj[k]
return r
}, 0)
})
console.log(data)
答案 3 :(得分:1)
在读取对象键之后添加过滤器
.filter(k=>!['KID','PID'].includes(k))
let Result = [{"01": 330,"02": 353,"03": 178,"04": 353,"KID": 10,"PID": 5},
{"01": 320,"02": 112,"03": 328,"04": 123,"KID": 11,"PID": 6},
{"01": 110,"02": 253,"03": 375,"04": 233,"KID": 12,"PID": 7}]
Result.forEach(item =>{
item["total"] = Object.keys(item).filter(k=>!['KID','PID'].includes(k))
.reduce((acc,value) => acc + item[value],0);
})
console.log(Result);