3

how to check a type of an Object or of an Array?

I'm trying to add an Object (and add only if it's Object) to some Array.

//1. should add this OBJECT to the array
var objToAdd11 : Object = {name: 'Zack', age: 24};
this.addObject(objToAdd11);

//2. should throw errorbecause this is ARRAY, and we need only OBJECTS
var objToAdd22 : Array  = [{name: 'Zack', age: 24}];
this.addObject(objToAdd22);

public  addObject(obj: any) : void {
   /*I need to check is obj parameter OBJECT OR ARRAY*/
   var myArray : Array = [1, "a", 3];

   function () {
       myArray.push(obj);
   }

   var newMyArray : Array = myArray;
}

2 Answers 2

2

You can use Array.isArray() to check if it's an array otherwise add it

var objToAdd11 : Object = {name: 'Zack', age: 24};
this.addObject(objToAdd11);

//2. should throw errorbecause this is ARRAY, and we need only OBJECTS
var objToAdd22 : Array  = [{name: 'Zack', age: 24}];
this.addObject(objToAdd22);

if(!Array.isArray(objToAdd11)){
 //add to list
}

Please check https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray?v=example

Hope it helps!!

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

Comments

0

You can check for object by Object.keys(obj).length > 0 && obj.constructor === Object. Hope it helps.

//1. should add this OBJECT to the array
var objToAdd11: Object = {name: 'Zack', age: 24};
this.addObject(objToAdd11);

//2. should throw errorbecause this is ARRAY, and we need only OBJECTS
var objToAdd22: Array  = [{name: 'Zack', age: 24}];
this.addObject(objToAdd22);

public  addObject(obj: any) : void {
   /*I need to check if obj parameter is OBJECT OR ARRAY*/
   var myArray: Array = [1, "a", 3];

   if(Object.keys(obj).length > 0 && obj.constructor === Object) {
      myArray.push(obj);
   } else {
      console.error("Obj is not an Object");
   }

   var newMyArray: Array = myArray;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.