Reputation: 209
Is there a way to check if array this.state.allBooks
contains both id:552
and name:'book2'
in the same index and return either true or false... I want to avoid using a for loop if possible.
// Array this.state.allBooks
O:{id:133, name:'book1'}
1:{id:552, name:'book2'}
2:{id:264, name:'book3'}
previously I've done something similar to the below code, but since array this.state.allBooks
has an id and a name I'm not sure what approach to take.
let boolValue = this.state.allBooks.includes(/* check if it includes a single value*/)
//Desired output
// 1.0) Does this.state.allBooks include both id:552 and name:'book2' in the same index ?
// a) if yes return true ... should be yes since both id:552 and name:'book2' are part of the same index '1'
// b) if no return false
Upvotes: 0
Views: 743
Reputation: 125
Using javascript's array method of some will return a boolean if any of the elements inside the array pass the test given to the method. Here this code iterates over the array checks if any element's id is 552 and name is 'book2'. If it finds any element to pass this test it will return true otherwise false.
// Array this.state.allBooks
const books = [{id:133, name:'book1'}, {id:552, name:'book2'}, {id:264, name:'book3'},]
let isObjIn = books.some(book => book.id === 552 && book.name === 'book2');
console.log(isObjIn); // logs true
Upvotes: 0
Reputation: 878
Hi you can use map function,
let state:any = {};
let boolValue:boolean = false;
state.allBooks = [
{id:133, name:'book1'},
{id:552, name:'book2'},
{id:264, name:'book3'}
];
state.allBooks.map(e=>{
if(e.id == '552' && e.name == 'book2'){
boolValue = true;
}
});
console.log(boolValue)
here is a working example link
Upvotes: 0
Reputation: 747
I think you can just use JavaScript's method some
of the array class. Some will return true if any of the elements in the array match the given predicate so the following code should do the trick:
let boolValue = this.state.allBooks.some(bookObject => bookObject.id === 552 && bookObject.name === 'book2');
Upvotes: 3
Reputation: 66103
You can use Array.prototype.find
to search for the entry. However, do note that internally the implementation of Array methods that involves searching and filtering always involve some kind of for
loop anyway.
const data1 = [{id:133, name:'book1'},{id:552, name:'book2'},{id:264, name:'book3'}];
const found1 = data1.find(({ id, name }) => id === 552 && name === 'book2');
console.log(found1); // { id: 552, name: 'book2' }
console.log(!!found1); // true
// Let's mutate the entry so it will not be found, for testing
const data2 = [{id:133, name:'book1'},{id:999552, name:'xxxbook2'},{id:264, name:'book3'}];
const found2 = data2.find(({ id, name }) => id === 552 && name === 'book2');
console.log(found2); // undefined
console.log(!!found2); // false
Upvotes: 0