13

In Angular 2 how do I check if a property is an array?

I have tried constructor but get a function as below:

function Array() { [native code] }

My Code:

let content: any = {id: '1324234', value:{id:null}};
if(content.value.constructor === 'Array'){
 console.log('It is an array');
} else {
 console.log('Not an array');
}
Ka Tech
  • 8,937
  • 14
  • 53
  • 78

1 Answers1

39
if(content.value instanceof Array){

See also Test for array of string type in TypeScript

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • Thanks for the prompt response! Works. – Ka Tech Dec 19 '16 at 09:08
  • Could you please tell how to check this in a template? – Vikram Singh Jan 18 '19 at 04:57
  • @VikramSingh You can't. You can put this code into a function and call the function from the template (which is usually a bad idea because of performance issues of calling functions from templates). Rather store the result in a variable and bind to this variable from the template. – Günter Zöchbauer Jan 18 '19 at 06:10
  • but i have dynamic object and i have to display key value pairs in html only if the value is not an Array. I am going with method approach. If you have any better idea please tell me. – Vikram Singh Jan 18 '19 at 07:13
  • Prepare a data structure that contains the data *and* the result of the type test and use this data structure in the template. – Günter Zöchbauer Jan 18 '19 at 07:18