0

I want to check if an object has only one property or only two properties and no other property in javascript.

Suppose I have an object like this.

const obj1 = {
   a : 'something'
}

OR

const obj2 = {
  a : 'somthing',
  b : 'somthing else'
}

Now how do I check if obj1 has only a and no other property? Also, how do check if obj2 has only a and b and no other property? Thanks for your time

Pranta
  • 518
  • 5
  • 15

2 Answers2

4
Object.keys(obj1).length == 1 && obj1.a

and

Object.keys(obj2).length == 2 && obj2.a && obj2.b

both utilize the number of keys.

expressjs123
  • 1,580
  • 1
  • 3
  • 17
1

You may use the following countobjkey function:

<script>
function countobjkey(var1)
{let size=0;
for(let k in var1) {
  size++
}
return(size);
}



var person = {fname:"John", lname:"Doe", age:25};
var car = {engine:"X4", brand:"Toyota", cc:'1300', color:'black'};

alert(countobjkey(person));
alert(countobjkey(car));



</script>
Ken Lee
  • 2,537
  • 2
  • 4
  • 21