Looking to navigate through a collection of objects using JavaScript

I'm seeking assistance with this code snippet I have written:

const parqueAutomotor = [];

parqueAutomotor[0] = {Brand: "Peugeot",
                      Model: "206",
                      Doors: 4,
                      Price: "$200.000,00"},

parqueAutomotor[1] =    {Brand: "Honda",
                        Model: "Titan",
                        Displacement: "125c",
                        Price: "$60.000,00"},

parqueAutomotor[2] =   {Brand: "Peugeot", 
                        Model: "208", 
                        Doors: 5, 
                        Price: "$250.000,00"},

parqueAutomotor[3] =   {Brand: "Yamaha",
                        Model: "YBR",
                        Displacement: "160c",
                        Price: "$80.500,50"
                        };


var i, item;

for (i = 0; i < parqueAutomotor.length; i++) {
    for (item in parqueAutomotor[i]) {
    console.log(item + ": " + parqueAutomotor[i][item] + " // ");
    }
}

The expected output in the console is:

Brand: Peugeot // Model: 206 // Doors: 4 // Price: $200.000,00
Brand: Honda // Model: Titan // Displacement: 125c // Price: $60.000,00
Brand: Peugeot // Model: 208 // Doors: 5 // Price: $250.000,00
Brand: Yamaha // Model: YBR // Displacement: 160c // Price: $80.500,50

However, the actual output I am receiving is not formatted correctly as requested.

Can anyone suggest how to resolve this issue while maintaining the specified format? Thank you!

Answer №1

Save each line as a variable and add double slashes "//" as a separator before each entry to avoid extra separators at the beginning and end of the line. Once you've built the complete line, display it on the console.

const vehicleFleet = [];

vehicleFleet[0] = {Brand: "Peugeot",
                    Model: "206",
                    Doors: 4,
                    Price: "$200,000.00"},

vehicleFleet[1] =    {Brand: "Honda",
                      Model: "Titan",
                      Displacement: "125cc",
                      Price: "$60,000.00"},

vehicleFleet[2] =   {Brand: "Peugeot", 
                     Model: "208", 
                     Doors: 5, 
                     Price: "$250,000.00"},

vehicleFleet[3] =   {Brand: "Yamaha",
                     Model: "YBR",
                     Displacement: "160cc",
                     Price: "$80,500.50"
                    };


var i, element;

for (i = 0; i < vehicleFleet.length; i++) {
    let row ="";
    let startRow = true;
    for (element in vehicleFleet[i]) {
        if (!startRow)
            row += " // ";
        else
            startRow = false;
        row += element + ": " + vehicleFleet[i][element];
    }
    console.log(row);
}

Answer №2

To efficiently loop through an array, you can utilize Array.forEach. By combining this with Object.entries to access key/value pairs and converting them into strings, then joining the results using Array.join:

const vehicleList = [];

vehicleList[0] = {
    Brand: "Peugeot",
    Model: "206",
    Doors: 4,
    Price: "$200.000,00"
  },

  vehicleList[1] = {
    Brand: "Honda",
    Model: "Titan",
    Displacement: "125cc",
    Price: "$60.000,00"
  },

  vehicleList[2] = {
    Brand: "Peugeot",
    Model: "208",
    Doors: 5,
    Price: "$250.000,00"
  },

  vehicleList[3] = {
    Brand: "Yamaha",
    Model: "YBR",
    Displacement: "160cc",
    Price: "$80.500,50"
  };


vehicleList.forEach(item => console.log(Object.entries(item).map(pair => `${pair[0]}: ${pair[1]}`).join(' // ')));

Answer №3

To print multiple console.log() statements in one line, you need to construct the entire string first and then output it as a single line.

const carInventory = [];

carInventory[0] = {
    Make: "Peugeot",
    Model: "206",
    Doors: 4,
    Price: "$200,000.00"
  },

  carInventory[1] = {
    Make: "Honda",
    Model: "Titan",
    Displacement: "125cc",
    Price: "$60,000.00"
  },

  carInventory[2] = {
    Make: "Peugeot",
    Model: "208",
    Doors: 5,
    Price: "$250,000.00"
  },

  carInventory[3] = {
    Make: "Yamaha",
    Model: "YBR",
    Displacement: "160cc",
    Price: "$80,500.50"
  };


var i, item;

for (i = 0; i < carInventory.length; i++) {
  let row = "";
  for (item in carInventory[i]) {
    row += item + ": " + carInventory[i][item] + " // ";
  }
  console.log(row)
}

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 can I incorporate the Three.js scene demonstration into Vue 3?

Looking to integrate the Three.js beginner example for creating a scene [1] into a Vue.js 3 project using JavaScript (not TypeScript)? [1] main.js import * as THREE from 'three'; const scene = new THREE.Scene(); const camera = new THREE.Perspe ...

Despite containing elements, Array.length incorrectly reports as 0 in React, JavaScript, and TypeScript

I have been working on storing persistent data for my Electron app using electron-json-storage. Initially, I tried using neDB but encountered an error, so I switched to another method. However, it seems that the issue is not with neDB but rather with my ow ...

Is there a way to void a delayed input event?

After reading this How to delay the .keyup() handler until the user stops typing? post, we have grasped how to implement delays. However, is there any suggestion on how to cancel a delayed event? Take a look at this In the scenario given, I want nothing t ...

Unable to render chart using angularjs-nvd3-directives

After developing a basic Angular - nvd3 project, I decided to utilize liveData.example from the angularjs-nvd3-directives Library on Github. To tailor it for my needs, I made enhancements to integrate with my REST API. Here is the REST API endpoint: http ...

Troubleshooting: Directives in Angular 4 not recognizing RegEx patterns

I have developed a directive that validates the input in a text field, allowing users to enter numbers, dots, and commas. However, the validator only seems to work for numbers and not for commas and dots. import { Directive, ElementRef, HostListener } fro ...

What is the process of passing a function into a custom react context provider that allows for state editing?

Below is the code snippet I am currently working with: import React, { useState } from 'react' export const NumberContext = React.createContext() export function NumberProvider({ children }) { const [numbers, setNumbers] = useState([]) fu ...

Tips for simultaneously dragging multiple items individually using JqueryUi sortable

I have conducted extensive research but have not found a suitable solution for my specific case. Below is the simplified version of my HTML structure: <div> <div> <ul class="sortable"> <li id="item-1"> ...

Dynamic font sizing in CSS allows text on a webpage to

I am working on creating a dynamic screen using AngularJS. Within this screen, there are objects with a specific size: .item { margin: auto; margin-bottom: 10px; width: 11vw; height: 11vw; text-overflow: ellipsis; overflow: hidden; } These i ...

Having difficulty grasping the significance of the data received from the API response

Currently, as I am working on my personal Portfolio for a Web Developer course, I have encountered an issue with correctly implementing my API to retrieve information from the database. Previously, I faced no problem when using a .json file, but now, I am ...

What is the best approach to create a form wizard with validation using Vue.js?

I recently completed a Vue.Js project where I created a wizard based on a video tutorial. However, I am facing issues with form validation using the 'is-valid' and 'is-invalid' CSS classes that I have defined. Here is my code: <div c ...

Changing a functional component into a class-based component

Looking to convert a functional component into a class-based one in React. However, encountering an error - ReferenceError: Cant find variable: Props. The main concern is where to add props when moving from the functional component to a class-based one to ...

How can I empty the value of a UI widget (such as an input field, select menu, or date picker) in Webix UI?

Is there a way in Webix UI to clear widget values individually, rather than collectively based on form id? I'm looking for a method using a mixin like $$(<form-id>).clear(). I need control of individual elements, so is there a proper way to res ...

Is there a way to extract and store the numerical values from a string in Selenium IDE?

Is there a way to extract the confirmation number 135224 from the example below for use on another website? store text | xpath=//b[contains(., 'Authorization Request - Confirmation Number : 135224')] | string Unfortunately, I'm encounterin ...

Calculate the total of the smallest values in three columns as they are updated in real-time

I'm facing an issue with dynamically adding the sum of the 3 lowest values entered in columns. The Total Cost Field is not displaying any value, and changing the type from number to text results in showing NaN. I've tried various approaches but h ...

The function ajax does not recognize response.forEach as a valid function

When I try to use ajax for fetching data from MySQL using PHP and JavaScript, I encounter a function error stating "response.forEach is not a function". Despite looking through various posts on this issue, none of the suggested solutions have been able to ...

library for lightgallery with additional lg-thumbnail functionality

I am currently working on setting up a lightgallery with the lg-thumbnail plugin in a WordPress installation. If you want more information about the API, you can visit this link: API Documentation For specific details on the lg-thumbnail plugin, you can ...

Selecting a JSON object at random

My data is stored in JSON format. [ ["Apple","A"], ["Orange","O"], ["Grape","G"], ["Kiwi","K"] ] Is there a way to randomly select an array item from this data (e.g. ["Grape","G"])? var letterNum = ""; $.ajax ( { url:"getletter.json" }).done( ...

Tally of number series in an array

If my array looks like [0, 2, 4, 10, 10, 10, 10, 2, 5, 3, 2, 10, 10, 5, 7, 4, 10, 10, 10, 10] How do I determine the number of times a sequence of 10's occurs with at least 3 repetitions. In this example, the output would be 2 because there are 2 s ...

The jspdf function is not displaying any images in the PDF file

I am new to coding and encountered an issue when trying to download images in reactjs. After clicking the download button, I only receive a blank pdf file. https://i.stack.imgur.com/0XJcC.png The function in my react code that attempts to generate the p ...

Obtain the outline shape in ThreeJS (duplicate border)

When working with a geometry, I often need to view it from different angles. For example, if I position my camera from the top, I want to be able to extract the outline of the geometry as a new shape. This allows me to then Extrude this shape further. In R ...