反应本机JSON过滤

时间:2018-07-25 22:15:21

标签: react-native

我正在学习React Native,并致力于通过JSON feed进行过滤。我可以筛选出一组数据,但我希望在该组中进一步筛选。在“ 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>)

}

}

2 个答案:

答案 0 :(得分:0)

这将过滤项目$ 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);
    });
}

答案 1 :(得分:0)

像这样更新您的文字

<Text>
   {this.state.filteredItem.map(item=>item.id)}
</Text>

item.id更改为您想要的道具

相关问题