0

I have some codes

var weibo = { weibo: { url: '//testurl.com', icon: 'fa fa-weibo' } }
var mail = { mail: { url: '//testurl.com', icon: 'fa fa-envelope' } }
var github = { github: { url: '//testurl.com', icon: 'fa fa-github' } }

var [key] = Object.keys(weibo)
var name = weibo[key]
console.log(weibo[key])

I want to get object from weibo and store into name variable

But name show [object object]

enter image description here

I am not use alert from What does [object Object] mean? (JavaScript)

key is a string weibo enter image description here

I just want to store variable into name, why chrome dev tools show [object object]?

console.log() works, it show corrent object info enter image description here

Update please see my gif


nuclear
  • 3,181
  • 3
  • 19
  • 38
  • Don't use square brackets around `key` variable when you're defining it! – FZs Oct 20 '18 at 05:02
  • I don't see anything wrong with the bracket notation. Why this should cause the problem? – Teemoh Oct 20 '18 at 05:14
  • 1
    The code seems to be fine, and does work (https://codesandbox.io/s/3y8lmj3q8m). What version of chrome are you using? – phpcoderx Oct 20 '18 at 05:16
  • @phpcoderx I use `Version 69.0.3497.100 (Official Build) (64-bit)`, I also think it should works, It's a bug or not? I copy your codes and run in my chrome dev snippet, but first console.log() show [object object], But when I open my dev tools, your codes have correct logs in my console – nuclear Oct 20 '18 at 08:51
  • @FZs Why? it's `array destructuring`. I think it same as `var key = Object.keys(weibo)[0]` – nuclear Oct 20 '18 at 08:55
  • Thanks for the info. Now you will probably never ever use global variables anymore :D – Teemoh Oct 20 '18 at 13:39

3 Answers3

4

This had me thinking for a while, turns out there is a window.name global variable defined in browsers (MDN:Window.name).

According to MDN: window.name will convert all values to their string representations by using the toString method.

When toString is applied to an object, the output will be [object object].

So either enclose your piece of code within its own scope (probably inside a function) or rename your name variable.

phpcoderx
  • 570
  • 5
  • 16
  • 1
    Yes! you are right! you must be an great developer! It works now when I enclosure using `(function(){})()`, This question will remind me of global scope variable – nuclear Oct 20 '18 at 10:13
1

use

var key = Object.keys(weibo)
var name = key[0]
hossein sedighian
  • 1,711
  • 1
  • 13
  • 16
1

It is because you have created "weibo" as an object, and you passing this to a primitive data type reference " name ".

Irrfan23
  • 362
  • 5
  • 17
  • key is `"weibo"`, So I think weibo[key] === weibo["weibo"], but from dev tools, name show as `[object object]` – nuclear Oct 20 '18 at 08:59