在Fetch [Reactjs]中过滤JSON对象

时间:2017-08-23 09:27:11

标签: javascript reactjs fetch

我定义了这个状态:

 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的对象数组:

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();
    }

从fetch中获取并保存在this.state.products内的JSON对象如下所示:

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

enter image description here

如前面提到的那样,使用此行this.setState({products:responseData})我可以将products传递到我希望显示nameprice的表格:

<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中的另一个对象中:

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:"angel@magnifique.club"
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

enter image description here

该对象是通过其他功能获得的:

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");
            });
    }

目前我可以在没有过滤器的情况下打印所有产品。问题是如何使用客户喜欢的产品过滤我获得的产品。如何将存储在数组中的收藏产品的ID传递给getProducts中使用的获取。

0 个答案:

没有答案