0

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.

1
  • Please show us your logic to search for object in your array. Commented May 31, 2017 at 12:00

5 Answers 5

1

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))

Sign up to request clarification or add additional context in comments.

Comments

1

You can use some:

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

Comments

0

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;
     }
    }
}

Comments

0

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

Comments

0

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 })

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.