处理未格式化的数据阵列

时间:2016-09-23 21:54:34

标签: javascript arrays

我正在使用一个函数来返回一些这样的数据:

<body>
    <h1>Simple Math Test</h1>
    <p>Q1: 5 + 9 = ??</p>
        <button id = "Q1A" onclick = "answerPrompt1()">Answer</button>
        <button id = "Q1C" onclick ="showResult()">Check</button>
    </p>
</body>

这是我自己写的功能:

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

有没有办法重写这个函数,所以我有一个合适的数组对象(最好的解决方案,但更复杂?)或者有没有办法重新格式化我上面的数据数组,所以我可以这样:

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

1 个答案:

答案 0 :(得分:1)

是的,只需更改密钥:

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