简体   繁体   中英

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.

You can use some :

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

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM