如何在fetch中输出特定的响应?



目前我的下拉列表有大约30+输出,但我想将列表减少到特定的项目,我不确定如何实现这一点。

我的API是什么样子~

{
"filter": "A",
"timestamp": "2021-08-05T15:52:02.489962-04:00",
"contracts": [
{
"contractCode": "Code 1",
"contractName": "Name of contract 1",
"status": "A"
},
{
"contractCode": "Code 2",
"contractName": "Name of contract 2",
"status": "A"
},
{
"contractCode": "Code 3",
"contractName": "Name of contract 3",
"status": "A"
}
]
}

假设我只想输出代码1和代码3如何在取回调用中过滤呢?也有可能设置一个html复选框来选择我想输出的每个代码?

My Fetch call

fetch('API LINK')
.then(response => response.json())
.then(data => makeContract(data.contracts))
.catch(error => console.log(`Oh no! ${error}`))
const makeContract = (contracts) => {
const body = document.getElementById('contractCode');
contracts.forEach((contracts) => {
const htmlTemplate = `
<option>${JSON.stringify(contracts.contractCode).slice(1, -1)}</option>
`;
body.innerHTML += htmlTemplate;
});
};

function demo() {
const include = Array.from(document.querySelectorAll('[name=code]:checked')).map(e=>e.value);
const contracts = sample().contracts;
contracts.forEach(contract => {
if (include.includes(contract.contractCode)) { console.log(contract); }
});
}
function sample() {
return {
"filter": "A",
"timestamp": "2021-08-05T15:52:02.489962-04:00",
"contracts": [
{
"contractCode": "Code 1",
"contractName": "Name of contract 1",
"status": "A"
},
{
"contractCode": "Code 2",
"contractName": "Name of contract 2",
"status": "A"
},
{
"contractCode": "Code 3",
"contractName": "Name of contract 3",
"status": "A"
}
]
};
}
<input type="checkbox" name="code" id="code1" value="Code 1">
<label for="code1">Code 1</label>
<input type="checkbox" name="code" id="code2" value="Code 2">
<label for="code2">Code 2</label>
<input type="checkbox" name="code" id="code3" value="Code 3">
<label for="code3">Code 3</label>
<input type="button" value="Try it" onclick="demo()">


fetch('API LINK')
.then(response => response.json())
.then(data => makeContract(data.contracts))
.catch(error => console.log(`Oh no! ${error}`));
const makeContract = contracts => {
const body = document.getElementById('contractCode');
const include = Array.from(document.querySelectorAll('[name=code]:checked')).map(e=>e.value);
contracts.forEach(contract => {
if (!include.includes(contract.contractCode)) { return; }
const htmlTemplate = `
<option>${JSON.stringify(contract.contractCode).slice(1, -1)}</option>
`;
body.innerHTML += htmlTemplate;
});
};

最新更新