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;
解决方案
includes
不适用于对象。尝试find
或findIndex
代替。我也认为你的检查是错误的。您需要检查是否items
已选择productId
,如果是,则更新其计数。
const addCart = (productsId) => {
setCount(count + 1)
data.forEach((product) => {
let index = items.findIndex(itm => itm.id === product.id && productId === product.id)
if (index >= 0) {
let newProduct = { ...items[index] }
newProduct.count += 1
setItem( [...item, [index]: newProduct ])
} else {
setItem(item.concat(product))
}
})
}
推荐阅读
- python - Google Cloud Dataflow 更新管道
- excel - VBA 编码 - - 如果单元格包含某个文本
- python - 如何在给定参数之前的第 N 个字符上拆分字符串(Python)
- amazon-web-services - 如何在不使用托管 UI 的情况下通过谷歌登录将用户添加到 cognito 中的用户池
- python - 提取主机名、时间戳、HTTP 请求方法、URI 和协议
- office365 - MS Office 插件的跨平台兼容性
- java - Spring cloud sleuth 3.0.1 使用 logback 在日志中生成 traceid 和 spanid
- javascript - Promise 解析函数返回未定义
- python - 如何在美丽汤的标签中找到子元素或标签?
- karate - 有没有办法从内部调用的特征文件中更新特征文件的值