Mithun Nath
Mithun Nath

Reputation: 523

How to search in a Javascript Object array?

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

Answers (5)

alnavarro
alnavarro

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

prasanth
prasanth

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

muratgozel
muratgozel

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

Dino
Dino

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

str
str

Reputation: 44969

You can use some:

let containsId => id => item => item.id === id;
let isIdInList = lists.some(containsId(10));

Upvotes: 1

Related Questions