我在一個名為 data.json 的檔案中有一些嵌套的 Json。我fetch用來讀取檔案,然后想根據用戶是否在網站的下拉串列中選擇了特定選項進行一些過濾。
var jsonData = [{"type": "FeatureCollection",
"features": [
{"type": 'Feature', "properties": {"id": 1}, "geometry": {"type": "Point", "coordinates": [-80.71, 28.34]}},
{"type": 'Feature', "properties": {"id": 2}, "geometry": {"type": "Point", "coordinates": [-79.89, 28.45]}},
{"type": 'Feature', "properties": {"id": 2}, "geometry": {"type": "Point", "coordinates": [-60.79, 28.32]}}
]}
]
我想根據該"properties": {"id": #}欄位對這組特征進行一些過濾。例如,如果用戶選擇了與該 id 匹配的值,則將其保留在我的結果顯示資料中,否則將其洗掉。
我正在嘗試通過如下所示的 Promise 做某事。我是 JavaScript 新手,但.filter下面代碼中的使用是我試圖讓它作業的嘗試。
我想要實作的理想解決方案:
我在美國地圖上顯示了一張資料地圖,其中包含相對于id我提到的領域的某些位置的點。我希望用戶能夠通過 Javascript 中的下拉工具單擊其中一個 ID,然后通過他們的選擇,將 JSON 資料過濾為僅屬于該 ID 的功能。例如,您將在資料上使用的傳統過濾器。
function filterIds(data) {
let idFilter= document.getElementById("id-filter");
let selection = idFilter.addEventListener('change', function(event) {
return this.value;
});
data.features.map((element) => {
// spread out our array of data and filter on specific property (namely, the id key)
return {...element, properties: element.filter((property) => property.id=== selection)};
});
async function getData(url) {
let response = await fetch(url);
let data = await response.json();
// console.log(data);
return data;
};
getData("../data/processed/data.json") // fetch raw data
.then(data => filterIds(data));
uj5u.com熱心網友回復:
這是一種嘗試的技術,它將流程稍微更改為:
- 用戶加載頁面
- 頁面為下拉串列分配一個事件監聽器
- 頁面將 data.json 加載到全域變數中
只有當用戶更改下拉串列時,它才會檢查以確保 data.json 已加載,然后執行所需的過濾。
// global var to store "data" from getData
let processedData;
// assign the listener once, on page load
document.getElementById("id-filter").addEventListener('change', function(event) {
if (!processedData) return; // still no processedData available
let selection = this.value;
let newData = processedData.features.map((element) => {
// spread out our array of data and filter on specific property (namely, the id key)
return {...element, properties: element.filter((property) => property.id === selection)};
});
// do something with newData
});
const setData = (data) => {
// this just stores data in the global processedData variable
processedData = data;
};
async function getData(url) {
let response = await fetch(url);
let data = await response.json();
return data;
};
// call getData once, on page load
getData("../data/processed/data.json") // fetch raw data
.then(data => setData(data));
uj5u.com熱心網友回復:
您需要對過濾器功能進行一些更改 -
function filterIds(data) {
let idFilter= document.getElementById("id-filter");
let value = null;
let selection = idFilter.addEventListener('change', function(event) {
value = this.value;
});
data.features.map((element) => {
const properties = element.filter((property) =>
property.id=== value);
return {...element, properties};
});
}
要解決此問題Uncaught (in promise) TypeError: element.filter is not a function,您需要對 getData 函式進行以下更改 -
async function getData(url) {return await fetch(url).then((res) => res.json())};
此外,您必須在全域級別的過濾器函式之外設定事件偵聽器。
uj5u.com熱心網友回復:
也許沒有必要過濾,因為您在它之前進行了索引。根據您正在做的事情,它可能會更快。
表格或圖表的基本示例。
var jsonData = [{"type": "FeatureCollection",
"features": [
{"type": 'Feature', "properties": {"id": 1}, "geometry": {"type": "Point", "coordinates": [-80.71, 28.34]}},
{"type": 'Feature', "properties": {"id": 2}, "geometry": {"type": "Point", "coordinates": [-79.89, 28.45]}},
{"type": 'Feature', "properties": {"id": 2}, "geometry": {"type": "Point", "coordinates": [-60.79, 28.32]}}
]}
]
// Create a select element
document.body.append(Object.assign(document.createElement("select"), {id: "select" }))
// Count features and create options
for (let i = 0; i < jsonData[0].features.length; i ){
document.getElementById("select").append(
Object.assign(document.createElement("option"), {textContent: i })
)
}
// Read by index at selection change
select.addEventListener("change", (e) => {
let selected = e.target.selectedOptions[0].textContent // Cast to integer
console.log(jsonData[0].features[selected])
})
uj5u.com熱心網友回復:
// ... mocked API call ...
async function fetchData() {
return new Promise(resolve =>
setTimeout(() => resolve({
data: [{
"type": "FeatureCollection",
"features": [{
"type": 'Feature',
"properties": {
"id": 1
},
"geometry": {
"type": "Point",
"coordinates": [-80.71, 28.34]
}
}, {
"type": 'Feature',
"properties": {
"id": 2
},
"geometry": {
"type": "Point",
"coordinates": [-79.89, 28.45]
}
}, {
"type": 'Feature',
"properties": {
"id": 2
},
"geometry": {
"type": "Point",
"coordinates": [-60.79, 28.32]
}
}]
}]
}), 2000)
);
}
// one time data transformation in order to avoid filtering later.
function getFeaturesMapGroupedByPropertiesId(featureList) {
return featureList.reduce((map, featureItem) => {
const { properties: { id } } = featureItem;
(map[id] ??= []).push(featureItem);
return map;
}, {});
}
function renderDropdownOptions(node, idList) {
const { options } = node;
// delete/reset the `options` collection.
options.length = 0;
// put/add initial default selected option item.
options.add(new Option('select an id', '', true, true));
idList.forEach(id =>
options.add(new Option(`feature ${ id }`, id))
);
}
function handleFeatureChangeWithBoundFeaturesMap({ currentTarget }) {
const idBasedFeaturesMap = this;
const featureId = currentTarget.value;
console.log(
`id specific feature list for "id ${ featureId }" ...`,
idBasedFeaturesMap[featureId],
);
}
async function main() {
console.log('... trigger fetching data ...');
const { data } = await fetchData();
console.log('... fetching data ... done ...', { data });
console.log('... synchronize dropdown data ...');
const idBasedFeaturesMap =
getFeaturesMapGroupedByPropertiesId(data[0].features);
// console.log({ idBasedFeaturesMap });
// //console.log(Object.keys(idBasedFeaturesMap));
const dropdownNode = document.querySelector('select#feature');
if (dropdownNode) {
renderDropdownOptions(
dropdownNode,
Object.keys(idBasedFeaturesMap),
);
dropdownNode
.addEventListener(
'change',
handleFeatureChangeWithBoundFeaturesMap.bind(idBasedFeaturesMap)
);
}
}
main();
.as-console-wrapper {
min-height: 100%;
width: 80%;
left: auto!important;
}
body { margin: 0; }
<select id="feature">
<option value="">... initializing ...</option>
<!--
<option value="1">feature 1</option>
<option value="2">feature 2</option>
//-->
</select>
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/439299.html
標籤:javascript 数组 json
上一篇:typeMismatch(Swift.Array<Any>,Swift.DecodingError.Context(codingPath:[CodingKeys(stringValue:&
下一篇:如何正確撰寫此Json
