1

Why after I replaced if (typeof obj[key] == 'object') with if (typeof obj.key == 'object') the result is not expect. this is my code:

var animals = {
  bird: {
    color: 'blue',
    action: {
      fly: true,
      nesting: true,
      swim:false
    },
    eat:'insect'
  }
};
function GetObjectKeys(obj, keys) {
 for (let key in obj) {
     //if (typeof obj.key == 'object')
       if (typeof obj[key] == 'object') 
  {
           keys.push(key);
           GetObjectKeys(obj[key], keys);
       } 
else {
           keys.push(key);
       }
   }
   return keys;
}
arrKeys = [];
GetObjectKeys(animals, arrKeys); 

//
- result expect:
[
  'bird',    'color',
  'action',  'fly',
  'nesting', 'swim',
  'eat'
]
- result when use if (typeof obj.key == 'object') :
[ 'bird' ]

Thank you!

AkaJack
  • 43
  • 5
  • Welcome to StackOverflow! You'll need to paste in here the results you see and then the results that you _expect_ to see. This will help us determine what you are trying to do. – Josh Maag Jun 20 '20 at 03:46
  • When you use `obj.keys` it looks for a property named literally **"key"** INSIDE the object. BUT there is none with that name! More info: [Is it possible to add dynamically named properties to JavaScript object?](https://stackoverflow.com/questions/1184123/is-it-possible-to-add-dynamically-named-properties-to-javascript-object) – Vinay Jun 20 '20 at 05:43

4 Answers4

1

The key on your dot notation example(obj.key) is a string, your obj doesn't have the property named key, hence it's undefined.

You are passing in a variable in your bracket notation, for (let key in obj) loops all the property names in your object obj. so obj[key] basically equals to obj['bird'] from your first function call.

Toxnyc
  • 1,350
  • 7
  • 20
1

Answer

The way I see it, When you use for...in expression, key is being the key with string type. like "key1","key2","key3'

so, when you use key like obj.key it is like obj."key. So it occur some error.

so you can use dynamic property keys like obj[key].

Reference

Stark Jeon
  • 1,107
  • 9
  • 24
1
  • obj.key equal obj["key"] will look for "key" as a property in your object, and obviously there is no key property in animals object ==> obj.key equal obj["key"] is undefined. ==> you got unexpected result.
  • obj[key] is dynamically take the value of key to pass in the notation. E.g const key = "name" => obj[key] equal obj.name. It is "bird" in your case obj[key] equal obj["bird"] equal obj.bird
Tony Nguyen
  • 3,298
  • 11
  • 19
0

using obj[key] is better for this type of use. Look here:

var obj = {key: 1, key2: 2}
var key = 'key2';

obj.key = 3;
obj[key] = 4; // result: {key: 3, key2: 4}
Rick
  • 1,710
  • 8
  • 17