尝试用另一个对象数组筛选一个对象数组



我想添加一个购物车到我的应用程序。我需要过滤产品数组通过匹配ID在我的购物车数组中包含一个对象然后显示在我的平面列表中。我已经测试了,以确保我可以使用其他方法过滤产品列表,如includes()。

我无法使当前代码工作。

我已经简化了我的代码到最低的可读性。

<View>
<Text>
Cart
</Text>
<FlatList
data={this.props.products.products.filter(product => this.props.cart.cart.some(el => el === product.id))}
renderItem={renderMenuItem}
keyExtractor={item => item.id.toString()}
/>
</View>

这是我的db。保存数组的Json文件

"products": [
{
"id": 0,
"name": "Ezywhip Pro",
"category": "chargers",
"label": "",
"featured": false,
"description": "Ezywhip Pro Cream Chargers, Made by MOSA",
"image": "images/ezywhip.png",
"quantity": 0,
"price": 0
},
{
"id": 1,
"name": "Ezywhip Pro",
"category": "ezy",
"label": "",
"featured": false,
"description": "Ezywhip Pro Cream Chargers, Made by MOSA",
"image": "images/ezywhip.png",
"quantity": 50,
"price": 40
},
{
"id": 2,
"name": "Ezywhip Pro",
"category": "ezy",
"label": "",
"featured": false,
"description": "Ezywhip Pro Cream Chargers, Made by MOSA",
"image": "images/ezywhip.png",
"quantity": 100,
"price": 70
}
],
"cart": [
{
"id": 1
}
]

结果当前为空Flatlist。提前感谢您的任何反馈。

您的'some()'方法中缺少购物车数组项的'id'属性。

例如:this.props.cart.cart.some(el => el.id === product.id))

完整的代码是

data={this.props.products.products.filter(product => this.props.cart.cart.some(el => el.id === product.id))}

这是因为您的cart是一个以id为属性的对象数组,因此在您的代码中,el引用购物车对象,并且与el.id检查相等性。

我试着把它分解,这样它就可以作为一个JS片段运行,这样你就可以在下面看到它的运行。

const products = [
{
"id": 0,
"name": "Ezywhip Pro",
"category": "chargers",
"label": "",
"featured": false,
"description": "Ezywhip Pro Cream Chargers, Made by MOSA",
"image": "images/ezywhip.png",
"quantity": 0,
"price": 0
},
{
"id": 1,
"name": "Ezywhip Pro",
"category": "ezy",
"label": "",
"featured": false,
"description": "Ezywhip Pro Cream Chargers, Made by MOSA",
"image": "images/ezywhip.png",
"quantity": 50,
"price": 40
},
{
"id": 2,
"name": "Ezywhip Pro",
"category": "ezy",
"label": "",
"featured": false,
"description": "Ezywhip Pro Cream Chargers, Made by MOSA",
"image": "images/ezywhip.png",
"quantity": 100,
"price": 70
}
]
const cart = [
{
"id": 1
}
]
const filtered = products.filter(product => cart.some(el => el.id === product.id))
console.log('Filtered: ', filtered)

根据我的理解,您想要显示购物车及其相应产品的列表。你可以迭代购物车数组获取id,然后过滤product array获取配套产品

<View>
<Text>
Cart
</Text>
{ 
this.props.carts.forEach(cart => 
(<FlatList
data={this.props.products.filter(product => product.id === cart.id)}
key={cart.id}/>)
);
}
</View>

的一些建议:

  • "cart"输入db。Json应该是"carts"如果是数组
  • 应该有另一个字段,如"cartId"产品对象