从获得一串字符串获取键值对数组
问题描述:
我使用的是npmscraper。我在下面有两个几乎相同的函数,我想基本上将它们返回的结果组合到键值对格式中的一个数组中。从获得一串字符串获取键值对数组
首先函数返回[ '桔子', '苹果', '葡萄']
第二个函数返回[ '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);
'我想是一样的东西'这不是一个有效的JavaScript构造......你的意思是'[]'是'{}'...''return ='???真?你是否声称你的代码实际上产生了当前的输出? –