2017-05-31 111 views
0

我正在使用Angular 2与Typescript。如何在Javascript对象数组中进行搜索?

我有一个看起来像这样的对象数组;

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

所有我想要做的是,我需要在数组中找到一个特定的ID后返回true或false值。

我找到了一个字符串示例如下。

myFunction() { 
var fruits = ["Banana", "Orange", "Apple", "Mango"]; 
var a = fruits.indexOf("Apple"); 
var d = a >= 0 ? true : false 
console.log(d); 
} 

但是,当我在我的情况中应用这个,它没有工作。

+0

请告诉我们你的逻辑阵列中搜索对象。 –

回答

1

Array#find方法尝试

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

1

您可以使用some

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

最简单的解决办法是通过列表数组进行迭代,并检查是否object.id等于所请求的ID。

checkID(id: number){ 
    for(var i = 0; i < lists.length; i++) { 
    if(lists[i].id == id){ 
    return true; 
    } 
    else{ 
     return false; 
    } 
    } 
} 
0

下面的代码将返回true如果particularId列表false另有发现。

const foundObjects = lists.filter(obj => obj.id == particularId) 
return !foundObjects || foundObjects.length === 0 
0

你可以使用一些,它将返回true,如果确认至少一个情况是真实的。 尝试是这样的:

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 }) 
相关问题