javascript - 您如何检查数组中是否存在相同的项目并执行其他操作?
问题描述
我正在尝试将项目推送到数组中,但我希望如果数组中有类似的项目,只需将计数更新为 1,而不是再次在数组中添加该项目。我已经尝试了很多东西,例如include()
函数,但它没有按预期工作,因为当我在映射每个产品时放置 item.includes(product) 时,每当我添加一个项目时,每个项目的计数都会更新产品...例如,当我添加一个产品时,对于一个项目,另一个项目也会获得该更新...
import React, {useState, useContext} from 'react'
import data from './data.js'
import useCountsContext from './context/useCountsContext.js'
var uniqid = require('uniqid');
function Shop({ data }) {
const {count, setCount} = useContext(useCountsContext)
const {item, setItem} = useContext(useCountsContext)
const addCart = (productsId) => {
setCount(count + 1)
data.forEach((product) => {
if (item.includes(product)) {
product.count += 1
} else if (product.id === productsId) {
setItem(item.concat(product))
}
})
}
console.log(item)
return (
<div>
<h1>Shop</h1>
<div className="div___shop">
{data.map(({id, img, button}) => (
<>
<img className="img___shop" key={id} src={img}></img>
<div key={id}>
<button onClick={() => addCart(id)}>{button}</button>
</div>
</>
))}
</div>
</div>
)
}
export default Shop
我的数据文件:
import diCaprio from './img/diCaprio.jpg'
import steveJobs from './img/steveJobs.jpg'
import lips from './img/lips.jpg'
import buda from './img/buda.jpg'
import spaceDog from './img/spaceDog.jpg'
import astroNube from './img/astroNube.jpg'
import banksy from './img/Banksy.jpg'
import banksyDJ from './img/banksyDJ.jpg'
var uniqid = require('uniqid');
const data = [{
id: uniqid(),
title: "Steve Jobs",
img: steveJobs,
homeImg: steveJobs,
button: "add to cart",
count: 0
},
{
id: uniqid(),
img: diCaprio,
homeImg: diCaprio,
button: "add to cart",
count: 0
},
{
id: uniqid(),
img: lips,
homeImg: lips,
button: "add to cart",
count: 0
},
{
id: uniqid(),
img: buda,
homeImg: buda,
button: "add to cart",
count: 0
},
{
id: uniqid(),
img: spaceDog,
button: "add to cart",
count: 0
},
{
id: uniqid(),
img:astroNube,
button: "add to cart",
count: 0
},
{
id: uniqid(),
img: banksy,
button: "add to cart",
count: 0
},
{
id: uniqid(),
img:banksyDJ,
button: "add to cart",
count: 0
}
]
export default data;
解决方案
item
是一个产品列表(数组)并且product
是一个对象。您不能includes
在包含对象的数组上使用,您可以使用通用for
循环forEach
、 或现代find
在您的 items 数组中搜索产品
const addCart = (productsId) => {
setCount(count + 1)
data.forEach((product) => {
const exists = item.findIndex((i) => i.id === product.id) > -1;
// if check is on title
// const exists = item.findIndex((i) => i.title === product.title) > -1;
if (exists) {
product.count += 1
} else if (product.id === productsId) {
setItem(item.concat(product))
}
})
}
OP评论后更新
import React, {useState, useContext} from 'react'
import data from './data.js'
import useCountsContext from './context/useCountsContext.js'
var uniqid = require('uniqid');
function Shop({ data }) {
const {count, setCount} = useContext(useCountsContext)
const {item, setItem} = useContext(useCountsContext)
const addCart = (productsId) => {
setCount(count + 1)
// grab the product object from data array
const product = data.find((d) => d.id === productsId);
// if product is not found
if (product == null) {
throw new Error("Invalid ProductId");
}
// check if product already exists in item list
// grab the index of the product in the item list
const exists = item.findIndex((i) => i.id === product.id);
// if index is -1, the product doesn't exists
if (exists === -1) {
// add to item array
setItem(item.concat(product));
} else {
// product already exists
// increase the count
const cart = [...item]; // create a Shallow copy of cart
cart[exists].count += 1; // increment the count
setItem(cart); // update the cart state
}
}
return (
<div>
<h1>Shop</h1>
<div className="div___shop">
{data.map(({id, img, button}) => (
<>
<img className="img___shop" key={id} src={img}></img>
<div key={id}>
<button onClick={() => addCart(id)}>{button}</button>
</div>
</>
))}
</div>
</div>
)
}
export default Shop
推荐阅读
- c# - 如何交换 2 位数字并找到较大的结果?
- android - 向 Realme 和 Oppo 发送短信
- search - 在图形数据库(neo4j)中搜索用户,其中单个用户可以有多个(相似而不是重复)实例
- vaadin8 - Vaadin Charts Addon 4.0.0 API - 需要将闪烁的图像或 CSS 添加到数据系列
- browser - 等待 fetch.body ReadableStream 完成
- php - 轮播图像正在堆叠,如何阻止它们堆叠?
- javascript - 从显示在所有组件上方的侧边栏 Material UI 创建组件
- javascript - 正则表达式在路径中使用参数
- javascript - Next.js 路由器参数不断给我未知的关键警告
- c - execvp 不执行用户输入给出的命令