What is the best way to show nested objects in JavaScript?

let paragraph = document.createElement('p');
document.body.appendChild(paragraph)

const fruit = { 
  type: 'Apple',
  properties: {
   color: 'Green',
   price: {
     bulk: '$3/kg',
     smallQty: '$4/kg'
   }
  }
};

let text = ''
for (let key in fruit) {
  text += fruit[key] 
 };

paragraph.innerHTML = text;

When viewing this in the browser, I am seeing Green[object Object]. Thank you.

///////////////

Answer №1

When you reach the 2nd round of iteration, you will encounter data in the form of an object, hence the specific output you are observing.

To modify this behavior, simply convert apple[x] to a string by using JSON.stringify(apple[x]). This adjustment will yield the following result:

"Red"{"unitPrice":"$2/kg","quantity":"$5/kg"}

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

Steps to transfer the content of a label when the onclick event occurs

Seeking advice on how to send the dynamically varying value of a label upon clicking an anchor tag. Can anyone recommend the best approach to passing the label value to a JavaScript function when the anchor is clicked? Here is a sample code snippet: < ...

Display time series data from PHP by utilizing Flot Charts in jQuery

After receiving data from a database, which is formatted using PHP and returned as a JSON response for an Ajax call, I encountered an issue. Everything works fine and the data is plotted except when the X-Axis contains dates, in which case nothing gets plo ...

Obtain asynchronous state in VueJS without the need for intricate v-if conditions

I am working on an application that heavily relies on Vue-Router and Vuex for state management. Within the Dashboard component, important user information is displayed. This data is fetched asynchronously from a database by Vue and then stored in Vuex. T ...

What is the best way to create a promise in a basic redux action creator?

My function add does not return any promises to the caller. Here's an example: let add = (foo) => {this.props.save(foo)}; In another part of my application, I want to wait for add() to finish before moving on to something else. However, I know t ...

Retrieve all instances of a key-value pair within an object that share the same key

Here is some JSON data: [{"name":"David","text":"Hi"},{"name":"Test_user","text":"test"},{"name":"David","text":"another text"}] I am l ...

Exploring the depths of deep populating in Mongo and Node.js

I am currently struggling with a complex data population issue. var commentSchema = mongoose.Schema({ name: String }); var userSchema = mongoose.Schema({ userId: { type: String, default: '' }, comments: [subSchema] }); var soci ...

A guide on iterating through an array in vue.js and appending a new attribute to each object

To incorporate a new property or array item into an existing virtual DOM element in Vue.js, the $set function must be utilized. Attempting to do so directly can cause issues: For objects: this.myObject.newProperty = "value"; For arrays: ...

Sending information and HTML content from PHP to JavaScript using JSON

As a beginner to this, I acknowledge any noticeable mistakes. I am attempting to utilize an ajax call from Javascript to randomly select a movie from a database, generate some html containing information about the movie, and also return an array of inform ...

Why does the ReactJS MaterialUI Modal fail to update properly?

Recently, I encountered a curious issue with my Modal component: https://i.stack.imgur.com/dkj4Q.png When I open the dropdown and select a field, it updates the state of the Object but fails to render it in the UI. Strangely, if I perform the same action ...

Broadcast signals to an overarching frame

I have successfully embedded a chatbot (Angular 14 app) in an iframe and now I need to determine whether the frame should be minimized so it can fit within the parent container. My goal is to send custom events to the receiving frame. let iframeCanvas = do ...

What could be causing the data storage issue in the state?

Using axios, I am fetching data and storing it in a state variable useEffect(() => { getCartItems(); }, []); const [abc, setAbc] = useState([]); const getCartItems = async () => { let data = await CartApi.get(`/${store.getState().auth.user.id}/ ...

Is there a way to show text as symbols in Primeng components?

Check out this helpful example that demonstrates what I am attempting to achieve. I have implemented p-menu from primeng. Is there a method to convert text into symbols like &trade to ™ and &#8482 to ®? ...

The Angular JS routes are not properly loading the required file from the provided TemplateURL when receiving a response from Node

I am trying to retrieve data from a MySQL database using node (routes.js) and have the results injected into club.html, which is then dynamically updated in index.html using ng-view. However, it seems that the JSON response from node is displaying directly ...

Error: Unable to locate bundle.js when attempting to refresh the page with a specific ID in the URL

I encountered an issue where I tried redirecting a user to their profile page to display the profile information corresponding to it. Let's say we have http://localhost:8080/user/1 as an example. Upon redirecting the user using the navbar link, the pa ...

Experiencing a problem with the localhost connection

I've been trying to work on this issue using React and local host, but it keeps showing the direct file instead of the website. I've been stuck on this problem for the past 3-4 hours and still haven't been able to find a solution. I'm h ...

Laravel Mix fails to recognize VueJs integration in Laravel

Having an issue setting up VueJs with laravel 5.7 and mix where it keeps saying VueJs is not detected. I've already executed the npm install command. Below is my welcome view: <!doctype html> <html lang="{{ str_replace('_', '- ...

How to refresh a page in React when the browser's back button is pressed

In my React project using Material-UI, I have created a simple search form. On page A, users can input values in text boxes and select options from drop-down lists and checkboxes. The results are then displayed on page B. My issue arises when returning to ...

Mastering the art of carousel div creation with Bootstrap

Is there a way to create a carousel in Bootstrap 3 where only one div slides at a time, instead of three? I attempted to use divs instead of images in the traditional carousel structure, but it's not functioning as expected. I'm looking for some ...

Providing UI field attributes within server JSON data

Suppose I have numerous form fields that need to be displayed on the user interface. Additionally, in a standard Modify workflow, let's assume that these fields will have various attributes like value, mandatory, editable, disabled, label, regex (for ...

Issue: jQuery Datatable not functioning properly while attempting to populate the table through JavaScript.Explanation: The

I'm currently working on populating a table using JavaScript. However, I've encountered an issue where the table is being populated but it shows "No data available in table". Furthermore, when I try to interact with the data, it disappears. This ...