Объект Object: Что это значит?
Программирование и разработка
Объект Object — это строковое представление объекта. Вы можете увидеть этот текст, если используете alert (), например, для вывода объекта на экран. Вы можете просмотреть содержимое объекта, используя console.log (), JSON.stringify () или цикл for… in.
При разработке с использованием JavaScript многие из нас сталкивались с выводом: [object Object]. Когда я увидел это в первый раз, я пошёл к своему наставнику в то время и спросил: «Что это вообще значит?». Я был сбит с толку.
В этой статье мы расскажем об этом выходе и его значении. Мы поговорим о том, как вы можете преобразовать [object Object] в читаемый контент, с которым вы можете работать.
Что такое JavaScript Объект Object?
[Object Object] — строковая версия экземпляра объекта. Это значение возвращается программой JavaScript, если вы пытаетесь распечатать объект без предварительного форматирования объекта как строки.
Это синтаксис объекта Объект Object:
Неудивительно, что разработчики запутались в этом объекте: нет сообщений об ошибках или предупреждений, которые сообщают нам, что происходит. Давайте посмотрим на пример этого объекта в действии.
Объект Object пример JavaScript
Когда выполняется инструкция alert (), наш код возвращает [объект Object]. Наша программа пытается вернуть строковое представление того, что было передано в метод alert (). Но поскольку наш код видит это как объект, он сообщает нам, что вместо этого это экземпляр объекта.
Сообщение [object Object] не очень информативно. Но это не означает, что мы не можем видеть значения в нашем объекте. Давайте поговорим о способах чтения значений объекта.
Что внутри объекта?
Знать, что [объект Object] является экземпляром объекта, — это здорово, но мы хотим знать, что он находится внутри объекта. Это можно сделать тремя способами:
- Войдите в консоль с помощью console.log (<имя вашего-объекта>).
- Строгозуйте его с помощью JSON.stringify ().
- Используйте цикл for… in и просмотрите каждое свойство в отдельности.
Войти в консоль
Возможно, самый простой способ увидеть, что находится внутри объекта, — это записать объект в консоль. Оператор console.log () позволяет просматривать все значения в объекте JavaScript.
Рассмотрим следующий код:
Наш код объявляет объект с именем objA. Затем мы выводим значение объекта на консоль. Наш код возвращает:
Мы можем видеть значения в нашем объекте.
Используйте JSON.stringify ()
Метод JSON.stringify () преобразует объект JavaScript в строку. Затем мы можем манипулировать этой строкой.
Итак, мы можем использовать JSON.stringify () для преобразования объекта в строку. Затем мы могли бы использовать alert (), чтобы отобразить значение строки для пользователя:
Как и в нашем последнем примере, мы определили объект с именем objA. Затем мы используем метод JSON.stringify () для преобразования объекта в строку. Затем мы используем alert, чтобы отобразить значение строки в консоли.
Наш код открывает окно подсказки со следующим содержанием:
Используйте for… in Loop
Цикл JavaScript for… in позволяет нам перебирать содержимое объекта. Мы можем использовать этот цикл для вывода каждой отдельной пары ключ-значение.
Рассмотрим следующий код:
Мы объявили объект JSON под названием objA, как и в последних двух примерах. Затем мы используем цикл for… in для перебора содержимого этого объекта. Значение «ключа» представляет каждый ключ.
Мы используем значение «ключа» для доступа к ключу и objA [ключ] для доступа к значению, связанному с этим ключом. Наш код возвращает:
Мы используем конкатенацию строк, чтобы добавить двоеточие (:) между каждым ключом и значением. Это позволяет нам разделить ключи и значения, чтобы они были более читаемы в выводе нашего кода.
Заключение
JavaScript [объект Object] — это строковое представление объекта. Чтобы увидеть содержимое объекта, вы должны вывести его на консоль с помощью console.log () или преобразовать объект в строку. Или вы можете использовать цикл for… in для перебора объекта и просмотра его содержимого.
Вы хотите узнать больше о JavaScript? Ознакомьтесь с нашим полным руководством «Как изучить JavaScript», чтобы узнать о лучших учебных ресурсах и онлайн-курсах.
Why <> + <> gives "[object Object][object Object]" in JavaScript
J avaScript is huge and has unforgiven rules and specs we must abide to.
It’s operations give surprising results. One of the operations is the addition of two objects <> + <> .
Can you guess the result?
“[object Object][object Object]”
How and why should that be the result? Do you know?
If you don’t know, don’t worry. In this article, I will explain why that contraption was returned.
Check out this new API tool:
POSTly
Tool for managing your APIs right from your browser!
Now, this <> + <> is an addition of two objects.
JavaScript has a specification that all JavaScript engines must follow when running JavaScript code. Like that, the addition operator has its spec on what to do.
The spec says that:
Addition operation either performs string concatenation or numeric addition.
The above is the rule for addition in JavaScript.
See, the right and left values are converted to their primitive form first using the ToPrimitive function.
What is primitive or primitive form? In JS we have primitive data types and object data types:
Primitives are boolean, number, string, null, undefined while Objects are Objects, Array, Function, RegExp, Date.
So if the right or left value is a primitive the ToPrimitive function will just return it, no conversion needed. But if the right or left value is an Object, the ToPrimitive will try converting it to its primitive form.
As our right value <> and left <> values are Objects, the ToPrimitive will convert them to their primitive form.
Let’s see ToPrimitive spec:
We see that this ToPrimitive uses a hint to try to convert its input.
The method first checks the input is an Object because only Objects are to be converted to its primitive form. If the input is not an Object then it must be a primitive, so it just returns the input, no need for conversion to primitive.
This function was called without a hint, so the hint becomes “number” following the if checks. Next, the method checks @@toPrimitive is not defined in the object. If it’s defined the implementation in the @@toPrimitive will be called and the result returned as the primitive conversion of the object.
@@toPrimitive is the way JS gives the outside world power to add their implementation of ToPrimitive conversion. So instead of the built-in method to run theirs is run.
If @@toPrimitive is not defined, OrdinaryToPrimitive function is called with the hint “number” and the object, <> .
Let’s see the OrdinaryToPrimitive spec:
Here two methods are called: toString and valueOf(). OrdinaryToPrimitive will call each method on the argument, which must be an Object. Any method that returns a primitive value, the result will be returned to ToPrimitive. The order of their calls depends on the hint passed. If the hint is string, then toString is called first. If the hint is not a string then valueOf is called first. The hint must either be a string or a number.
Since the hint passed here is “number”, valueOf method will be called on our object first.
Note: Object provides functionality common to all JavaScript objects.
ToObject will be called with our object:
Below is ToObject conversion table:
Looking at the table, we see that what is returned is based on the argument. All the data types are converted to Objects. The primitives are converted to object by calling new on their corresponding data class. boolean primitives have new Boolean() to convert them to Boolean object, strings have new String(), null and undefined throw TypeError exception because they have no corresponding class. numbers, symbols have new Number() and new Symbol() called respectively. With new called, the primitives are converted to objects. objects are returned, no conversion needed because already they are Objects. Remember, JavaScript has two types of values, primitives, and objects.
We see that the argument is simply returned if it is an object, so in our case, the argument is <> which is an object so <> will be returned.
Now, the OrdinaryToPrimitive will see an object returned:
Since the result is an object, it will loop again to the toString and call the toString method on <> .
Let’s see the spec
This method tries to convert its input to string primitive value.
See, there are checks for undefined and null, they will return “[object Undefined]” and “[object Null]” respectively. Next, it calls ToObject on our argument which is our object <> , we know previously it will return the object. The result of the ToObject is passed through many checks to return the specified string.
There are checks for String, Function, Error, Boolean, Number, Date, Arguments, and RegExp.
The builtinTag is used to hold the string to return.
Ours is an object, so the method assigns “Object” to builtinTag.
The method then calls @@toStringTag on the object. @@toStringTag is the string description of an object.
JS uses the @@toStringTag to let users and objects define the string name of their objects.
So, here the method checks by calling @@toStringTag to see if the object has its defined string name.
A String valued property that is used in the creation of the default string description of an object. Accessed by the built-in method Object.prototype.toString.
In Object their is no @@StringTag, so the method uses the builtinTag value “Object”, then, it concatenates the builtinTag (“Object”) in between “[object “ and “]”, which will give:
and return the concatenation.
Also, the right value <> , will follow through the same process and return "[object Object]"
“[object Object]” + “[object Object]”
In the Addition operator, lprim will be “[object Object]” and rprim will be “[object Object]”. It will check if either lprim or rprim is a string:
The lprim and rprim both hold “[object Object]”, so they check succeeds. They are both converted to a string, as seen above. Which checking the ToString table returns the same string passed.
There is no need for conversion it’s already a string.
Back to the Addition operator, both lstr and rstr will be “[Object object]”. So, the lstr and rstr are concatenated:
“[Object object][Object object]”
Conclusion
You now, know why <> + <> gives "[Object object][Object object]" .
What does [object Object] mean? (JavaScript)
It means you are alerting an instance of an object. When alert ing the object, toString() is called on the object, and the default implementation returns [object Object] .
If you want to inspect the object, you should either console.log it, JSON.stringify() it, or enumerate over it’s properties and inspect them individually using for in .
As @Matt already explained the reason for [object object] , I would like to elaborate on how to inspect the object’s value. There are three options that come to my mind:
- JSON.stringify(JSONobject)
- console.log(JSONobject)
- or iterate over the object
The alert() function can’t output an object in a read-friendly manner. Try using console.log(object) instead, and fire up your browser’s console to debug.
That is because there are different types of objects in Javascript!
- Function objects:
stringify(function ()<>) -> [object Function]
- Array objects:
stringify([]) -> [object Array]
- RegExp objects
stringify(/x/) -> [object RegExp]
- Date objects
stringify(new Date) -> [object Date]
- Object objects!
stringify(<>) -> [object Object]
the constructor function is called Object (with a capital "O"), and the term "object" (with small "o") refers to the structural nature of the thingy.
When you’re talking about "objects" in Javascript, you actually mean "Object objects", and not the other types.
If you want to see value inside "[Object objects]" use:
[object Object]: What does this mean?
[object Object] is a string representation of an object. You may see this text if you use alert() to print an object to the screen, for instance. You can view the contents of an object using console.log(), JSON.stringify(), or a for…in loop.
When developing using JavaScript, many of us have encountered the output: [object Object]. When I saw this the first time, I went to my mentor at the time and asked: “What does this even mean?”. I was confused.
Find Your Bootcamp Match
- Career Karma matches you with top tech bootcamps
- Access exclusive scholarships and prep courses
Select your interest
First name
Last name
Phone number
By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.
This article aims to tell you about this output and what it means. We’ll talk about how you can translate [object Object] into readable content that you can work with.
What is JavaScript [object Object]?
[object Object] is a string version of an object instance. This value is returned by a JavaScript program if you try to print out an object without first formatting the object as a string.
This is the syntax for the [object Object] object:
It’s no wonder developers get confused about this object: there are no error messages or warnings that tell us what is going on. Let’s take a look at an example of this object in action.
[object Object] JavaScript Example
Take this example:
When the alert() statement runs, our code returns [object Object]. Our program tries to return a string representation of what was passed into the alert() method. But, because our code sees this as an object, it tells us that it’s an instance of an Object instead.
The [object Object] message is not very descriptive. But, this does not mean that we cannot see values in our object. Let’s talk about the ways in which we can read the values in an object.
What’s Inside the Object?
Knowing that [object Object] is an instance of an Object is great, but we want to know is inside the object. There are three ways to do that:
- Log to console with console.log(<your-object-name>)
- Stringify it with JSON.stringify(<your-object-name>)
- Use for…in loop and look at each individual property
Log to the Console
Arguably the easiest way to see what is inside an object is to log the object to the console. The console.log() statement lets you view all of the values in a JavaScript object.
Consider the following code:
Our code declares an object called objA. Then, we print out the value of the object to the console. Our code returns:
We can see the values in our object.
Use JSON.stringify()
The JSON.stringify() method converts a JavaScript object to a string. We can then manipulate this string.
So, we can use JSON.stringify() to convert an object to a string. Then, we could use alert() to display the value of the string to the user:
Like in our last example, we have defined an object called objA. Then, we use the JSON.stringify() method to convert the object to a string. We then use alert to display the value of the string to the console.
Our code opens up a prompt box with the following contents:
Use a for…in Loop
The JavaScript for…in loop lets us iterate over the contents of an object. We can use this loop to print out each individual key-value pair.
Consider the following code:
We have declared a JSON object called objA like we did in the last two examples. Then, we use a for…in loop to iterate over the contents of this object. The “key” value represents each key.
We use the “key” value to access the key and objA[key] to access the value associated with that key. Our code returns:
We use string concatenation to add a colon (:) between each key and value. This lets us separate the keys and values so they are more readable in the output of our code.
Conclusion
The JavaScript [object Object] is a string representation of an object. To see the contents of an object, you should print the object to the console using console.log() or convert the object to a string. Or, you can use a for…in loop to iterate over the object and see its contents.
Are you interested in learning more about JavaScript? Check out our complete How to Learn JavaScript guide for advice on top learning resources and online courses.
About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication.