Reputation: 523
I'm using Angular 2 here with Typescript.
I have an array of objects which looks like this;
lists: any [] = [
{title: 'Title1', content: 'Content1', id: 10},
{title: 'Title2', content: 'Content2', id: 13},
{title: 'Title3', content: 'Content3', id: 14},
{title: 'Title4', content: 'Content4', id: 16},
];
All I'm trying to do is that I need a true or false value returned after finding a particular id in the array.
I found an example with strings which is below.
myFunction() {
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var a = fruits.indexOf("Apple");
var d = a >= 0 ? true : false
console.log(d);
}
But when I apply this in my situation, it didn't work.
Upvotes: 0
Views: 67
Reputation: 1
You can use some, it will return true if the validation is true for at least one case. Try something like this:
let myArray = [
{title: 'Title1', content: 'Content1', id: 10},
{title: 'Title2', content: 'Content2', id: 13},
{title: 'Title3', content: 'Content3', id: 14},
{title: 'Title4', content: 'Content4', id: 16},
]
myArray.some(function(el){ return (el.id === 10) ? true:false })
Upvotes: 0
Reputation: 22490
Try with Array#find
method
var a= [
{title: 'Title1', content: 'Content1', id: 10},
{title: 'Title2', content: 'Content2', id: 13},
{title: 'Title3', content: 'Content3', id: 14},
{title: 'Title4', content: 'Content4', id: 16},
];
function check(id){
return a.find(a=> a.id == id) ? true : false;
}
console.log(check(10))
console.log(check(105))
Upvotes: 1
Reputation: 2589
Following code will return true
if particularId found in list false
otherwise.
const foundObjects = lists.filter(obj => obj.id == particularId)
return !foundObjects || foundObjects.length === 0
Upvotes: 0
Reputation: 8292
The simplest solution would be to iterate through lists array and check if object.id equals the requested ID.
checkID(id: number){
for(var i = 0; i < lists.length; i++) {
if(lists[i].id == id){
return true;
}
else{
return false;
}
}
}
Upvotes: 0