首页 > 解决方案 > 反应原生 JSON 过滤

问题描述

我正在学习 React Native 并致力于通过 JSON 提要进行过滤。我能够过滤到一组数据,但我希望在该组中进一步过滤。在“filteredItem”我可以得到下面的例子。

{"$id":"3","num":256,"event":"1234","description":"示例描述","startdate":"2018","enddate":"2019"}

如果我想过滤到类似于显示整个信息组的事件编号,我该怎么做?

componentDidMount() {
    return fetch('myurl')
        .then((response) => response.json())
        .then((responseJson) => {
            this.setState({
                isLoading: false,
                filteredItem: responseJson.filter(item => item.$id == 3),

            }, function () {
            });

        })
        .catch((error) => {
            console.error(error);
        });
}

render() {
    if (this.state.isLoading) {
        return (
            <View style={{ flex: 1, padding: 20 }}>
                <ActivityIndicator />
            </View>
        )
    }

    return (
        <View>
                <Text>
                 {JSON.stringify(this.state.filteredItem, null, 2)}
                </Text>                                                                                                                                                                                  
        </View>)

}

}

标签: react-native

解决方案


这将过滤项目 $id == 3 和项目事件 == 1234。

filteredItem: responseJson.filter(item => item.$id == 3 && item.event == 1234)

您可以使用 responseJson 来实现您想要的数组。

componentDidMount() {
    return fetch('myurl')
    .then((response) => response.json())
    .then((responseJson) => {
        // Put logic to process the responseJson here before setState
        console.log(responseJson)
        let filteredResponseJson = responseJson.filter(item => item.$id == 3)
        console.log(filteredResponseJson)

        this.setState({
            isLoading: false,
            filteredItem: filteredResponseJson,
        })
    })
    .catch((error) => {
        console.error(error);
    });
}

推荐阅读