display object issue with object display

I'm encountering a strange issue with my constructor objects in JS - when I try to view them, all I see is [object Object]. Can anyone help me figure out why this is happening? Check out the code snippet on MyCodeFiddle.

Answer №1

To populate a new array persArr with the values of properties from object pers, iterate over all the object keys.

To easily get all property values separated by commas, you can use persArr.join(', ').

function Person(first, last, age, eyecolor) {
  this.first = first;
  this.last = last;
  this.age = age;
  this.eyecolor = eyecolor;
}

var pers = new Person('John', 'Colin', 47, 'blue'),
    persArr = [];

Object.keys(pers).forEach(function(key) {
  persArr.push(pers[key]);
});

document.getElementById('data').innerHTML = persArr.join(', ');
#data {
  display: flex;
  width: 120px;
  height: 40px;
  border: 1px solid #000;
  background-color: #fff;
  justify-content: center;
  align-items: center;
}
<div id="data"></div>

You can also create a method in the Person prototype to retrieve the desired information:

function Person(first, last, age, eyecolor) {
  this.first = first;
  this.last = last;
  this.age = age;
  this.eyecolor = eyecolor;
}

Person.prototype.getInfo = function() {
  return `${this.first} ${this.last}, ${this.age} years old and ${this.eyecolor} eyes.`;
}

var pers = new Person('John', 'Colin', 47, 'blue');
document.getElementById('person').innerHTML = pers.getInfo();
<div id="person"></div>

If you need to print the object for debugging:

  • Output in console:

    console.log(pers);

  • Print as a string in the HTML using JSON.stringify():

    document.getElementById('data').innerHTML = JSON.stringify(pers, null, 4);

Answer №2

When objects are directly inputted into HTML for display, they will show up as [object object] due to default behavior.

If you want to properly display them in HTML, there are two methods:

1) Iterate through the object properties

for(var i in pers ) {
   document.getElementById("data").innerHTML =  document.getElementById("data").innerHTML + pers[i] + ',';
}

http://jsfiddle.net/upwLvhs5/2/

2) Convert the object to JSON string

 document.getElementById("data").innerHTML = JSON.stringify(pers) 

http://jsfiddle.net/upwLvhs5/3/

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How come my reducer isn't changing the state of my store with ImmutableJS?

I have the following code within my reducer: const copy_states = fromJS(state); const i_copy_jobs = copy_states.get('calendar_jobs').get(s_from_day_key).get(s_dept_id).get(s_job_id); let i_calend ...

Output the initial value and subsequently disregard any values emitted during a specified time interval

Check out my code snippet: app.component.ts notifier$ = new BehaviorSubject<any>({}); notify() { this.notifier$.next({}); } app.component.html <div (scroll)="notify()"></div> <child-component [inp]="notifier$ | async" /> ...

stopPropagation() halts the propagation in the opposite direction

I encountered an issue while attempting to create a non-clickable div. While it does stop propagation, it doesn't prevent what should be stopped and allows things that shouldn't be clickable. js //screen has set stopPropagation $("#smokeScree ...

Tips for determining whether the current request is an AJAX request in MVC3 view using JavaScript

I have a div with a maximum height and overflow set to auto. When the size of the div overflows, a scroll bar is automatically added. However, I have also set $("#itemsdiv").scrollTop(10000); so that the scroll bar is always at the bottom. Now, I want t ...

Proceed with downloading the file only when a checkbox has been ticked off and the form has been

Is there a way to make a PDF download only when a user checks a checkbox and submits the form, rather than just checking the checkbox and hitting submit? I am limited to using Jquery or plain javascript and do not have access to backend files. The checkbox ...

Best practices for organizing an array of objects in JavaScript

I have an array of objects with nested arrays inside, and I need to restructure it according to my API requirements. [{ containerId: 'c12', containerNumber: '4321dkjkfdj', goods: [{ w ...

Tips for injecting scripts into the head tag after an Angular component has been loaded

Currently, I am facing an issue with a script tag containing a Skype web control CDN. The script has been placed in the head section of my index.html file, but it is being called before the component that needs it has finished loading. Does anyone have a ...

Discover the position of the element that was clicked within the group of elements sharing the

Here is my HTML code: <input type="button" class="buttonclose marleft fleft clrPric" value="X"> <input type="button" class="buttonclose marleft fleft clrPric" value="X"> <input type="button" class="buttonclose marleft fleft clrPric" value= ...

Load the entire AngularJS webpage using AJAX requests

I'm facing a challenge where I need to integrate an entire legacy page, along with some AngularJS elements, into our new page using AJAX. Initially, all I could see was the raw AngularJS markup: Rank ID {{$index+1}} {{player.playerid}} Afte ...

Utilize jQuery to select the parent checkbox and mark it as checked

Currently, I am working on a JavaScript function that will automatically check the parent checkbox if a child checkbox is checked. I am implementing this using jQuery and here is my HTML code: <ul id="ulParent" style="margin: 0; padding: 0; list- ...

Is there a way to send a Map object to a script file using EJS?

I am facing an issue with passing a Map object to my client-side code. I have successfully used EJS and JSON.stringify(...) in the past for arrays, but it doesn't seem to work for Maps. When I try to console.log(myMap.keys()), I receive the following ...

Get the characters from a URL following a specific character until another specific character

Having some difficulty using JavaScript regex to extract a specific part of a URL while excluding characters that come after it. Here is my current progress: URL: With the code snippet url.match(/\/[^\/]+$/)[0], I am able to successfully extrac ...

Creating a customized design for a React application with the use of Scss and JavaScript variables

Is there a method to incorporate JavaScript variables into an SCSS file? For instance, I have a JavaScript file containing the following code: // sky blue const PRIMARY_COLOR = '#489FEF' export { PRIMARY_COLOR} and I would like to utilize it ...

Expecting a volumetric result can be deceiving when dealing with objects that have three flat

The problem at hand: When subtracting a cube from a sphere, an interesting result occurs where the z axis maintains its volume while the y and x axes create flat disks. This peculiar outcome is puzzling to me as I utilize the typical subtraction method wi ...

Issue encountered when making API requests in JavaScript that is not present when using Postman

Currently, I am developing a web application using express and one of the functionalities is exposed through an API with an endpoint on 'api/tone'. This API acts as a wrapper for one of Watson's services but I choose not to call them directl ...

Error encountered due to an unhandled promise rejection of type

I am currently using async/await to execute a query to the database and receive the result. However, I encountered an error in the browser console that says: Unhandled promise rejection TypeError: "games is undefined" In my code, there are two function ...

Guide on inserting a MUI datepicker string value into the object state

Currently, I am in the process of developing a todo-list application that includes fields for description, priority, and date. To capture the priority and description inputs, I utilize TextFields which trigger the {inputChanged} function. Within this funct ...

What is the best way to ensure that my theme button changer has an impact on all pages throughout my website, not only on the

Looking for some help here - I've got a button that changes the theme/colour of my website, but it only seems to work on the homepage and not on any other pages. Anyone know how I can fix this issue? Here's the JavaScript code: $(document).ready ...

Creating a text design that spans two lines using Scalable Vector Graphics (SVG

I am working with an SVG that displays strings pulled from an Array... {"label":"Here is an example of the string...", "value":4}, The text above is shown in an SVG element as... <text>Here is an example of the string...<text> I would like ...

Issue with bidirectional binding on angular material slide toggle not functioning as anticipated (Angular 4)

My angular material slide-toggle implementation seems to be working, but I'm facing an issue where it doesn't bind the value to the relevant variable as expected. // other irrelevant imports above.. import {MatDialog, MatDialogRef, MAT_DIALOG_DA ...