Javascript:如何从API提取特定数据?

时间:2019-09-16 01:02:11

标签: javascript rest fetch

我正在执行Javascript练习,并尝试使用提取请求显示特定数据。

我正在尝试显示来自api网址的titlebody中的数据。在获取undefinedbody数据时,由于某种原因,我继续获取title

如何使用当前的JS代码正确显示bodytitle中的数据?

感谢您的帮助,谢谢!

Javascript:

fetch('https://uqnzta2geb.execute-api.us-east-1.amazonaws.com/default/FrontEndCodeChallenge')
    .then(function (response) {
        return response.json();
    })
    .then(function (data) {
        appendData(data);
    })
    .catch(function (err) {
        console.log('This is an error');
    });

function appendData(data) {
    let mainContainer = document.getElementById("testdata");
    for (var i = 0; i < data.length; i++) {
        var div = document.createElement("div");
        div.innerHTML = 'Name: ' + data[i].id + ' ' + data[i].body;
        mainContainer.appendChild(div);
    }
}

1 个答案:

答案 0 :(得分:1)

bodytitleversionContent属性(它是一个数组)内...即data[i].versionContent[0].body,其中0总是存在,但在在某些情况下,您还拥有1甚至还有2-您需要所有版本还是仅最新版本?

最新,您可以做

fetch('https://uqnzta2geb.execute-api.us-east-1.amazonaws.com/default/FrontEndCodeChallenge')
    .then(function (response) {
        return response.json();
    })
    .then(function (data) {
        appendData(data);
    })
    .catch(function (err) {
        console.log('This is an error');
    });

function appendData(data) {
    let mainContainer = document.getElementById("testdata");
    var newData = data
    .filter(function(item) {
        return ["1", "2", "3"].includes(item.stepNumber);
    })
    .sort(function(a, b) {
        return +a.stepNumber - b.stepNumber;
    });
    for (var i = 0; i < newData.length; i++) {
        var div = document.createElement("div");
        var versionContent = newData[i].versionContent.slice().pop();
        div.innerHTML = newData[i].stepNumber + ' Name: ' + newData[i].id + ' ' + versionContent.body;
        mainContainer.appendChild(div);
    }
}
<div id='testdata'></div>

在ES2015 +

fetch('https://uqnzta2geb.execute-api.us-east-1.amazonaws.com/default/FrontEndCodeChallenge')
.then(response => response.json())
.then(appendData)
.catch(err => console.log('This is an error', err));

function appendData(data) {
    const mainContainer = document.getElementById("testdata");
    const steps = ["1", "2", "3"];
    data
    .filter(item => steps.includes(item.stepNumber))
    .sort((a, b) => +a.stepNumber - b.stepNumber)
    .forEach(({id, stepNumber, versionContent}) => {
        const div = document.createElement("div");
        const {title, body} = versionContent.slice().pop();
        div.innerHTML = stepNumber + ' Name: ' + id + ' ' + body;
        mainContainer.appendChild(div);
    });
}
<div id='testdata'></div>