2017-06-14 39 views
1

我想要獲取數組的最後一個元素的id。如何檢索Angular 2中數組的最後一個元素ID

這是我如何我的數組

let last = this.Array[this.Array.length-1]; 
console.log(last); 

這裏的最後一個元素取是基於陣列

Object {id: 48, title: "I'm used to this"} 
title: "I'm used to this" 
id: 48 
__proto__: Object 

這裏最後一個元素的控制檯上,我已經看過already-名單

How to retrieve the clicked ElementId in angularjs?
How to get the object's id?
how to get the id name in html for any object和更多,但我不能。

我只想訪問id : 48,任何人都可以幫助我這樣做。
在此先感謝。

+1

怎麼樣'的console.log(last.id);'? –

+0

它顯示了這一點 - 錯誤TS2339:'Object'類型中不存在屬性'id'。 –

+0

看起來你的linter配置存在更多問題,或者如果你配置瞭如此嚴格的linter規則,使用具體的類和接口而不是'Object'。 –

回答

3

只是做到這一點:

let last:any = this.Array[this.Array.length-1]; 
console.log(last.id); 
3

你可以做this.Array.slice(-1)[0].id,而slice你的原始數組也不會改變。

DEMO:

var array = [{ 
 
    id: 43, 
 
    title: "I'm used to this" 
 
},{ 
 
    id: 44, 
 
    title: "I'm used to this" 
 
},{ 
 
    id: 45, 
 
    title: "I'm used to this" 
 
},{ 
 
    id: 46, 
 
    title: "I'm used to this" 
 
},{ 
 
    id: 47, 
 
    title: "I'm used to this" 
 
},{ 
 
    id: 48, 
 
    title: "I'm used to this" 
 
}] 
 

 
console.log('last id : ' + this.array.slice(-1)[0].id)

更新

當你的陣列產品的Object類型,所以先將其轉換爲一些真正的class\interface型,喜歡的東西:

export interface arrayItem{ 
    id?: number; 
    title?: string; 
} 

然後定義數組類型,如:

你的陣列狀

this.Array : Array<arrayItem> = [ { 
    id: 48, 
    title: "I'm used to this" 
    }, 
    //your other array items 
] 
+0

這裏沒有結果 - 錯誤TS2339:'Object'類型中不存在屬性'id'。 –

+0

將你的對象轉換成你的對象的具體class \ interface,比如:'export interface arrayItem {id:number; title:string; }',然後使你的數組​​類型爲'Array ' – anoop

相關問題