簡體   English   中英

使用 fetch API 在 React 中過濾掉 API 響應中的字段

[英]Filter out the fields in API response in React using fetch API

我有如下所示的 API 響應,我需要將其過濾掉,以便我只能從中獲得幾個字段。 例如,我只需要描述和地點位置。

results: [{placeId: "BHLLC", placeLocation: "BUFR", locationType: "BUFR",…},…] 0: {placeId: "BHLLC", placeLocation: "BUFR", locationType: "BUFR",…} binControl: "Y" description: "BUFR - Good Stock" locationType: "BUFR" ours: "Y" placeId: "BHLLC" placeLocation: "BUFR" transferIsUse: "Y" usable: "F"

我需要在 fetch.js 文件中傳遞 body 中的字段,如下所示

const body = { criteria, fields: ["description", "placeLocation", "whosPlace"], skip: 0, take: 2000 };

然后我試圖映射這樣的結果。 請注意,places 是對 API 調用函數的 fetches 調用的結果。

let result = [];
    if (places) {
        result = places.results.map(p => ({
            placeId: p.description, name: p.placeLocation
        }));
    }

fetch 文件中的 fetch 函數如下所示

export const fetchPlacesTo = async () => {

const criteria = [
    {
        anyOf: [
            {
                field: "WhosPlace",
                value: "L%",
                operator: "li"
            }
        ]
    }
];
const body = {
    criteria,
    fields: ["description", "placeLocation", "whosPlace"],
    skip: 0,
    take: 2000
};

const result = sessionManager
    .refreshFetch(
        `${**********_API_URI}/place/place`,
        fetchUtils.hwsGetRequest(body)
    )
    .then(parseResponse);

return result;

};

調用它的函數在下面

export const getPlacesTo = () => async dispatch => {
try {
    dispatch(loading.incrementLoading());

    const places = await fetches.fetchPlacesTo().catch(error => {
        console.log(error); //CRS: Change to logger
        dispatch(loading.setWarning(errors.ERROR_GET_DATA));
    });

    let result = [];
    if (places) {
        result = places.results.map(p => ({
            placeId: p.description, name: p.placeLocation
        }));
    }

    dispatch({
        type: constants.GET_LOOKUP_ENTITY,
        payload: {
            name: "placeIdToRepair",
            value: result
        }
    });

我想你想要 placeId 和 placeLocation 從響應到結果

var result=[]
var data={results: [{placeId: "BHLLC", placeLocation: "BUFR", locationType: "BUFR"},{placeId: "BHALC", placeLocation: "BAFR", locationType: "BAFR"},{placeId: "BHBLLC", placeLocation: "BUBFR", locationType: "BUBFR"}]}
data.results.map(p=>result.push({
            placeId: p.placeId, name: p.placeLocation
        }));
console.log(result)//(3) [{…}, {…}, {…}]
0:
placeId: "BHLLC"
name: "BUFR"
__proto__: Object
1:
placeId: "BHALC"
name: "BAFR"
__proto__: Object
2:
placeId: "BHBLLC"
name: "BUBFR"
__proto__: Object
length: 3

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM