Javascript 在React.js中过滤JSON数据

Javascript 在React.js中过滤JSON数据,javascript,json,reactjs,Javascript,Json,Reactjs,我将该州定义为: constructor(props){ super(props); this.state = { open: false, customers:[], customer:{}, products:[], product:{}, orders:[], order:{},

我将该州定义为:

 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
如前所示,通过此行
this.setState({products:responseData})
我可以将
products
传递到我想要显示
name
price
的表中:

<DataTables
     height={'auto'}
     selectable={false}
     showRowHover={true}
     columns={FAV_TABLE_COLUMNS}
     data={this.state.products}
     showCheckboxes={false}
     rowSizeLabel="Filas por página"
           />
如何筛选产品以仅显示客户最喜爱的产品?

客户端所有喜爱的产品都存储在数组
FavoriteSProducts
中的另一个对象中:

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
此对象通过以下其他函数获得:

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");
            });
    }
目前,我可以打印没有过滤器的所有产品。问题是我如何筛选我获得的产品,以及客户最喜欢的产品


创建一个新函数
getFavoriteProduct
,它看起来像这样

getFavouriteProducts() {
    fetch(all products)
    .then((response1) => {
        fetch(fav products)
        .then((resonse2) => {
            // filter response1 on the basis of response2
            this.setState({desiredState: desiredOutput})
        })
    })
} 
编辑: 您也可以从单个函数执行此操作

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

您应该使用过滤器和映射:

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" />
    )
}
isProductInFavorites(产品){
//TODO:如果当前产品在客户的收藏夹中,则返回true
}
render(){
const products=this.state.products
.filter((产品)=>此.isProductInFavorites(产品))
.map((产品)=>[product.name,product.price])
返回(
)
}
我不确定您是否需要数据数组或对象,但如果您需要对象,函数应该是
(product)=>{name:product.name,price:product.price}


另外,我想确保您知道fetch需要您检查响应的状态,如中所述。如果服务器在返回
getProducts

的列表之前管理每个产品的“收藏夹”状态可能更好,这样getProducts将与这个新函数冗余,对吗?当我得到第一个响应时,我是否应该使用
response.JSON()将数据传递到JSON格式
?您编写的所有内容都保留了下来,只需使用嵌套的
fetch
语句即可实现您的目标。我是否应该避免使用fetch函数并使用
const products=this.state.products.map((product)=>[product.name,product.price])
在我的
数据表上方
还是我误解了你?我想这是误解。您的
getProducts
看起来很好,而且似乎工作正常。我只需检查链接上显示的状态,以确保服务器没有返回错误。您的问题是您只想在产品列表中显示名称和价格。在不改变取货方法的情况下,使用地图是最好的选择。但重点不是要得到我所有的产品,而是要得到客户最喜欢的产品。我可能误解了这个问题。很抱歉我认为最好的方法是只进行一次获取,您的服务器应该在发送响应之前管理每个产品的喜爱状态。如果不能,可以使用与我使用的
.map
相同的方法,在产品列表上使用
.filter
,并且仅当产品位于favoriteProducts数组中时才返回true。我用过滤器示例编辑了我的答案。我不确定在哪里调用您的
getCustomers
,但是一旦您已经有了这两个列表,那么知道产品是否在产品收藏夹中的函数就不会太复杂了。
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" />
    )
}