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


6
  • Don't use square brackets around key variable when you're defining it! Commented Oct 20, 2018 at 5:02
  • I don't see anything wrong with the bracket notation. Why this should cause the problem? Commented Oct 20, 2018 at 5:14
  • 1
    The code seems to be fine, and does work (codesandbox.io/s/3y8lmj3q8m). What version of chrome are you using? Commented Oct 20, 2018 at 5: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 Commented Oct 20, 2018 at 8:51
  • @FZs Why? it's array destructuring. I think it same as var key = Object.keys(weibo)[0] Commented Oct 20, 2018 at 8:55

3 Answers 3

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.

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

1 Comment

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
1

use

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

1 Comment

I want to know why var name=weibo[key] not equal to console.log(weibo[key)
1

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

1 Comment

key is "weibo", So I think weibo[key] === weibo["weibo"], but from dev tools, name show as [object object]

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.