[英]From getting an array of strings to getting an array of key-value pairs
我正在使用npmscraper 。 我在下面有兩個幾乎相同的函數,我想將它們返回的結果基本上以鍵值對格式組合到一個數組中。
第一個函數返回['orange','apple','grape']
第二個函數返回['www.orange.com','www.apple.com','www.grape.com']
(非常簡化)要從foo.com抓取的示例數據###
<p>orange <a href="www.orange.com">click here</a></p>
<p>apple <a href="www.apple.com">click here</a></p>
<p>grape <a href="www.graphe.com">click here</a></p>
// Begin node app
var scraperjs = require('scraperjs');
// first function
scraperjs.StaticScraper.create('https://foo.com/')
.scrape(function($) {
return $(".entry p").map(function() {
return = $(this).text();
}).get();
})
.then(function(fruit) {
// after some cleaning up...
console.log(fruit)
//returns ['orange','apple','grape']
})
-----------------------
// second function gets the links
scraperjs.StaticScraper.create('https://foo.com/')
.scrape(function($) {
return $(".entry a").map(function() {
return = $(this).attr('href');
}).get();
})
.then(function(links) {
console.log(links)
// returns ['www.orange.com','www.apple.com','www.grape.com']
})
(編輯)我想要的是這樣的:
[{fruit: 'orange'; link 'www.orange.com'},{fruit: 'apple'; link 'www.apple.com'}]
因此,您將擁有兩個數組
var array1 = ['orange','apple','grape']; var array2 = ['www.orange.com','www.apple.com','www.grape.com'] // combining them to create an object var result = array1.reduce(function(obj, key, index) { obj[key] = array2[index]; return obj; }, {}); console.log(result);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.