2016-11-18 53 views
1

我試圖從產品結果頁中提取所有mpn值,其中數據以JSON-LD格式存儲。抓住前10個值,這是最理想的方式嗎?從頁面上的所有json-ld對象獲取屬性值的最佳方式是什麼?

(function(){ 
var mpns= document.querySelectorAll('script[type="application/ld+json"]'); 
var x = []; 
mpns.forEach(
    function(value){ 
     var a = JSON.parse(value.innerText).mpn; 
     x.push(a); 
    } 
); 
return x.slice(0,10); 
})(); 


<script type="application/ld+json"> 
{ 
    "@context": "http://schema.org/", 
    "@type": "Product", 
    "name": "Executive Anvil", 
    "image": "http://www.example.com/anvil_executive.jpg", 
    "description": "Sleeker than ACME's Classic Anvil, the Executive Anvil is perfect for the business traveler looking for something to drop from a height.", 
    "mpn": "925872", 
    "brand": { 
    "@type": "Thing", 
    "name": "ACME" 
    } 
    } 
} 
</script> 

回答

0

不,這不是好方法。因爲如果mpns數組的長度是1000000,那麼如果你只想要前10個元素,那麼push是什麼意思。

因此請嘗試循環代替

相關問題