简体   繁体   中英

Filter JSON data in React.js

I have this state defined:

 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,

        };
    }

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

This function is called in componentDidMount :

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

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

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"
           />

The table called is:

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

How can I filter the products to display only the favourite ones of the client?

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:"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

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.

CAPTURE OF THE CURRENT SITUATION: ALL PRODUCTS BEING DISPLAYED

CAPTURE FOR MELEXANDRE

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

You should use filter & map:

isProductInFavorites(product) {
    // TODO: Return true if the current product is in the Customer's favorites
}

render() {
    const products = this.state.products
        .filter((product) => this.isProductInFavorites(product))
        .map((product) => [product.name, product.price])
    return (
        <DataTables
         height={'auto'}
         selectable={false}
         showRowHover={true}
         columns={FAV_TABLE_COLUMNS}
         data={products}
         showCheckboxes={false}
         rowSizeLabel="Filas por página" />
    )
}

I'm not sure if you need an array of data or an object, but if you need an object, the function should be (product) => {name: product.name, price: product.price} .

Also, I'd like to make sure you know that fetch need you to check the status of the response, like described in the Github Polyfill . And it might be better if the server managed a "favorite" status on each product before returning the list for getProducts .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM