本文介绍了在React.js中过滤JSON数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已定义此状态:

 constructor(props){
        super(props);

        this.state = {
            open: false,
            customers:[],
            customer:{},
            products:[],
            product:{},
            orders:[],
            order:{},
            newForm:true,
            phoneNumbererror:null,
            shop:this.props.salon,
            value:'a',
            showTab:'none',
            slideIndex: 0,

        };
    }

使用包含fetch的以下函数,我收到一个对象数组responseData:

With the following function which contains a fetch, I recieve an array of objects with responseData:

getProducts(){
        fetch(
            DOMAIN+'/api/products/', {
                method: 'get',
                dataType: 'json',
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json',
                    'Authorization':'Bearer '+this.props.token
                }
            })
            .then((response) => response.json())
            .then((responseData) => {
                this.setState({products:responseData})
                console.log("Console log de products responseData");
                console.log(responseData);
            })
            .catch(function(e) {
                console.log(e);
            });
    }

此函数在 componentDidMount

componentDidMount(){
        this.getCustomers();
        this.getProducts();
    }

从获取中获取并保存在内的JSON对象this.state.products 看起来像这样:

The JSON object obtained from the fetch and kept within this.state.products looks like this:

Array(72)
0:
brand:{_id: "592d3092f42d775da9d38063", name: "Moroccanoil", __v: 0, created: "2017-05-30T08:42:58.242Z", photos: Array(0)}
created:"2017-06-14T18:46:52.508Z"
description:"Aporta una flexibilidad excepcional y proporciona un look hidratado y mate. Aplica una cantidad igual a la punta del dedo de esta arcilla filtrada, emulsiona entre las manos y distribúyela por el cabello. La fórmula de la arcilla purificada aporta al cabello textura y un acabado ligero y mate, y el Mineral Oil Finishing. Complex le proporciona un aspecto sano."
images:["https://storage.googleapis.com/magnifique-dev/olaplex 3.jpg"]
line:"Pruebadelproductolargo"
name:"Nombremuylargoaversicabe"
price:400
profile:"Decoloración"
salePrice:0
sex:["Mujer"]
size:"100 ML"
stock:400
videos:[""]
__v:19
_id:"5941849ce4fa0c7442b0f885"
__proto__:Object

如前面提到的那样,使用此行 this.setState({products:responseData})我可以传递产品到我想要的表格名称价格

As shown previously in the fetch, with this line this.setState({products:responseData}) I can pass products to the table where I want name and price to be displayed:

<DataTables
     height={'auto'}
     selectable={false}
     showRowHover={true}
     columns={FAV_TABLE_COLUMNS}
     data={this.state.products}
     showCheckboxes={false}
     rowSizeLabel="Filas por página"
           />

表格是:

const FAV_TABLE_COLUMNS = [
    {
        key: 'name',
        label: 'Producto'
    }, {
        key: 'price',
        label: 'Precio del producto'
    }
];

如何过滤产品以仅显示客户最喜欢的产品?

客户端的所有最喜欢的产品都存储在数组中的其他对象 favouritesProducts

All of the favourite products of the client are stored in this other object within the array favouritesProducts:

Array(22)
12:
app:{created: "2017-07-07T13:34:14.249Z"}
billingAddress:[]
cardLastNumbers:"5262"
cardSaved:"true"
created:"2017-06-30T09:51:59.869Z"
creditCard:
cardNumberSalt:
expirationSalt:
email:"[email protected]"
eyebrowType:"Pobladas"
eyelashType:"Rectas"
favouritesProducts:
Array(1)
0:
"594186cee4fa0c7442b0f942"
length:1
__proto__:
Array(0)
favouritesServices:[]
hairColor:"Rubio"
hairState:"Dañado"
hairType:"Medio"
loginType:[]
nailPolish:"Semipermanente"
nailType:"Naturales"
name:"AngelFBMag"
payerSaved:"true"
phoneNumber:
pictures:[]
platform:undefined
salt:
sex:"Mujer"
shippingAddress:[{…}]
shop:{_id: "59108159bc3fc645704ba508", location: {…}, settings: {…}, customers: Array(0), __v: 0, …}
surname:"Marquez"
__v:13
_id:"59561f3f1d178e1966142ad7"
__proto__:Object

此对象是通过其他函数获得的:

This object is obtained through this other function:

getCustomers(){
        fetch(
            DOMAIN+'/api/customers/shop/'+this.props.salon, {
                method: 'get',
                dataType: 'json',
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json',
                    'Authorization':'Bearer '+this.props.token
                }
            })
            .then((response) =>
            {
                return response.json();
            })
            .then((responseData) => {
                responseData.map(function (v) {
                    v.platform = v.app ? v.app.platform : null  })
                this.setState({customers:responseData})
                console.log(responseData);
            })
            .catch(function() {
                console.log("error");
            });
    }

目前我可以打印所有没有过滤器的产品。问题是如何使用客户喜欢的产品过滤我获得的产品。

Currently I can print all the products without a filter. The question is how can I filter the products that I obtain, with the favourite products of the client.

推荐答案

制作一个新功能 getFavouriteProduct 看起来像这样

Make a new function getFavouriteProduct that would looks something like this

getFavouriteProducts() {
    fetch(all products)
    .then((response1) => {
        fetch(fav products)
        .then((resonse2) => {
            // filter response1 on the basis of response2
            this.setState({desiredState: desiredOutput})
        })
    })
}

编辑:
您也可以通过单一功能完成此操作。

edit:You can to do this from a single function as well.

getEverything() {
    fetch(data_by_get_product)
    .then((response1) => {
        fetch(data_by_get_customer)
        .then((resonse2) => {
            // filter response1 on the basis of response2
            this.setState({states_changed_by_getProduct: response1})
            this.setState({states_changed_by_get_customer: response2})
            this.setState({desiredOutput: filteredOutput}}
        })
    })
}

这篇关于在React.js中过滤JSON数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 13:38