简体   繁体   中英

From getting an array of strings to getting an array of key-value pairs

I'm using npmscraper . I have two nearly identical functions below, which i want to basically combine the results they return into one array in key-value pair format.

First function returns ['orange','apple','grape']

Second function returns ['www.orange.com','www.apple.com','www.grape.com']


(very simplified) sample data to scrape from 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']
    })

(EDITED) What I'd like is something like:

[{fruit: 'orange'; link 'www.orange.com'},{fruit: 'apple'; link 'www.apple.com'}]

so, you'll have two arrays

 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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM