Project contains 7 cards , each card has own ID. I selected this ID . I have data in JS file , this data has 7 objects with ID , I want compare card ID with data ID , IF THIS IDs WILL MATCH , THEN WILL PRINT IT . console.log show me this
3 = card ID
(7) [1, 2, 3, 4, 5, 6, 7] = data file shows me array
How to change this array , I could compare card ID ?
const cardbody = document.querySelectorAll('.card')
cardbody.forEach(function(btn) {
console.log(btn) // it shows me current card
btn.addEventListener('click', function(e) {
const bt = e.currentTarget.dataset.id
console.log(bt) // 3
// data from JS file this return arrays
const dataid = cabins.map(function(item) {
return item.id
})
console.log(dataid) //(7) [1, 2, 3, 4, 5, 6, 7]
if(dataid === bt ) {
console.log('red')
}
})
})
CodePudding user response:
If you just need to know if the bt
is in any of the id
properties, use the some()
method. You don't need to create an array first.
cardbody.forEach(function(btn) {
console.log(btn) // it shows me current card
btn.addEventListener('click', function(e) {
const bt = e.currentTarget.dataset.id
console.log(bt) // 3
if (cabins.some(item => item.id == bt)) {
console.log('red')
}
})
})
CodePudding user response:
const arr = [1, 2, 3, 4, 5, 6, 7];
const id = 3;
// existance
if (arr.includes(id)) {
console.log(`${id} exists`);
}
// findIndex
if (arr.indexOf(id) >= 0) {
console.log(`${id} found at arr[${arr.indexOf(id)}]`);
}