Daniyal
Daniyal

Reputation: 1

Javascript: console.log Javascript object

var friends = {};

friends.steve = {
    firstName : "Steve",
    lastName : "Jobs",
    number: "(206) 555-5555",
    address: ['One Microsoft Way','Redmond','WA','98052'] 
};

function list(obj) {
    for(var key in obj) {
        if(key instanceof Object == true) {
        console.log(obj[key].join(", "));
        } else {
        console.log(obj[key]);
        }
   }
}   

Hi, I wanted to loop object friends.steve and console.log each of it's property, till now every thing is working, but I wanted that when my code reaches address array of my friends.steve object, it should log this address array like "One Microsoft Way, Redmond, WA, 98052" instead of like array, can anybody please help me with that how to do it. thanks

Upvotes: 0

Views: 257

Answers (3)

Shaunak D
Shaunak D

Reputation: 20626

Demo Fiddle

  • You need to check the value = obj[key] in case of an array. key instanceof Object will always return false.
  • Try using isArray() or instancof Array instead of Object.

var friends = {};

friends.steve = {
    firstName: "Steve",
    lastName: "Jobs",
    number: "(206) 555-5555",
    address: ['One Microsoft Way', 'Redmond', 'WA', '98052']
};
list(friends.steve);

function list(obj) {
    for (var key in obj) {

        if (Array.isArray(obj[key])) {    //Or if(obj[key] instanceof Array) {

            console.log(obj[key].join(','));

        } else {

            console.log(obj[key]);

        }
    }
}

Result:

"Steve" 
"Jobs"
"(206) 555-5555"
"One Microsoft Way,Redmond,WA,98052" 

Upvotes: 1

Royi Namir
Royi Namir

Reputation: 148514

don't count on if (obj[key] instanceof Object) {

However - you can do this :

   for(var key in obj) {
        if(key =='address') {
        console.log(obj[key].join(", "));
        } else {
        console.log(obj[key]);
        }
   }

So in your example :

for(var key in friends.steve ) {
        if(key =='address') {
        console.log(friends.steve[key].join(", "));
        } else {
        console.log(friends.steve[key]);
        }
   }

result :

Steve VM204:6
Jobs VM204:6
(206) 555-5555 VM204:6
One Microsoft Way, Redmond, WA, 98052 

Upvotes: 0

Scimonster
Scimonster

Reputation: 33399

You should be checking if the value is an object. The key will always be a string.

if(obj[key] instanceof Object == true) {

Maybe also use Array.isArray(obj[key]).

Upvotes: 0

Related Questions