首页 > 解决方案 > 如何对属性值进行求和和除法

问题描述

有这个变量:

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 作为总和。

建议?

标签: javascript

解决方案


您应该循环遍历 中的属性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);

推荐阅读