Simon Breton Simon Breton - 2 months ago 6
Javascript Question

Dealing with unformatted data array

I'm using a function which is returning me some data like this :

[{url1: "number1"},{url2: "number2"},{url3: "number3"},etc...]


Here is the function, which I didn't write myself :

const getNbShares = function() {
return Promise.map(urls, requestPromise)
.map((htmlOnePage, index) => {
const $ = cheerio.load(htmlOnePage);
const share = $('.nb-shares').html();
let shareTuple = {};
shareTuple[urls[index]] = share;
return shareTuple;
})
.catch((e) => console.log('We encountered an error' + e));
}


Is there a way to rewrite this function so I have a proper array object (the best solution but more complicated ?) or is there a way to reformat the data array I have above so I can have something like this :

[{url:"url1",value: "number1"},{url:"url2",value: "number2"},{url: "url3", value: "number3"},etc...]

Answer

Yes, just change the keys:

const getNbShares = function() {
    return Promise.map(urls, requestPromise)
                  .map((htmlOnePage, index) => {
                    const $ = cheerio.load(htmlOnePage);
                    const share = $('.nb-shares').html();
                    let shareTuple = {};

                    // set `url` to `urls[index]`
                    shareTuple.url = urls[index];

                    // then set the `value` to `share`
                    shareTuple.value = share;

                    return shareTuple;
        })
        .catch((e) => console.log('We encountered an error' + e));
}