javascript - 如何对属性值进行求和和除法
问题描述
有这个变量:
var pico = {
"dc:title": 0,
"dc:identifier": 0,
"dc:subject": 0,
"dc:type": 0,
"pico:preview": 0,
"dc:isReferencedBy": 0,
"dcterms:license": 0,
"pico:licenseMetadata": 0,
};
这个json响应:
{
'$':{
'xmlns:pico':'http://purl.org/pico/1.0/',
'xmlns:dc':'http://purl.org/dc/elements/1.1/',
'xmlns:dcterms':'http://purl.org/dc/terms/',
'xmlns:xsi':'http://www.w3.org/2001/XMLSchema-instance',
'xsi:schemaLocation':'http://purl.org/pico/1.0/ http://purl.org/pico/1.0/pico.xsd'
},
'dc:description':{
_:'L’antica porta urbica, incorporata negli edifici circostanti, fu ridotta a un solo fornice. Sul lato interno, Madonna col Bambino e santi, affresco del sec. XIV.',
'$':{
'xml:lang':'it'
}
},
'dc:identifier':'57926',
'dc:subject':{
_:'http://culturaitalia.it/pico/thesaurus/4.0#mura_fortificazioni',
'$':{
'xsi:type':'pico:Thesaurus'
}
},
'dc:title':{
_:'Arco delle due Porte, Siena',
'$':{
'xml:lang':'it'
}
},
'dc:type':{
_:'PhysicalObject',
'$':{
'xsi:type':'dcterms:DCMIType'
}
},
'dcterms:isReferencedBy':{
_:'http://www.touringclub.com/monumento/toscana/siena/arco-delle-due-porte.aspx',
'$':{
'xsi:type':'dcterms:URI'
}
},
'dcterms:spatial':{
_:'PlaceName=via Stalloreggi ; city=Siena ; province=SI',
'$':{
'xsi:type':'pico:PostalAddress'
}
}
}
如果 JSON 响应中也存在来自变量的属性,我将为该属性分配值 1,如果不存在,则为值 0。
然后我将获得的总和除以预期值 8 以获得填充字段的比率。
我做的:
for (var key in item.metadata["pico:record"]) {
pico[key] = pico[key] || 1;
pico[key] != pico[key] || 0;
}
...
let somma = 0;
for (var property in pico) {
console.log(property);
if (pico.hasOwnProperty(property)) {
somma += pico[property];
}
}
console.log(somma / 8);
但是,结果我得到的是 1 而不是 0.72。这是因为我制作的脚本计算的是属性而不是值。
然后我根据这个问题处理了这个问题。再次,我有 8 作为总和。
建议?
解决方案
您应该循环遍历 中的属性pico
,而不是 JSON 响应。而且您的逻辑运算符完全错误。
var somma = 0;
for (var key in pico) {
var found = item.metadata["pico:record"].hasOwnProperty(key) ? 1: 0;
pico[key] = found;
somma += found;
}
console.log(somma/8);
推荐阅读
- c++ - E0145 成员“boost::filesystem::path::separator”可能未初始化 & 使用 vcpkg 在 VS2017 中出现 LINK2019 错误
- python - 在 `distutils.setup(...)` 中选择 Visual Studio 版本
- javascript - Puppeteer + Pixelmatch:比较 Mac 和 TravisCI Linux 中的屏幕截图
- c - 将十进制转换为二进制的 C 程序 - 只有 64 位以下的值才是准确的
- javascript - 如何区分承诺链中的操作错误和程序员错误?
- data-science - 考虑到销售额有自然增长,如何建立统计模型来确定网站内容的更新是否促进了销售额
- javascript - 我将如何测试具有内部承诺的功能?
- vba - 遍历文件夹中的所有 Excel 工作簿并将所有公式转换为值
- javascript - 微服务架构和 MySQL 数据库分页
- ms-access - MS Access 打印页边距重置。