Output the contents of a nested object

After setting up a variable containing music library data...

 var library = {
   tracks: { t01: { id: "t01",
               name: "Code Monkey",
               artist: "Jonathan Coulton",
               album: "Thing a Week Three" },
        t02: { id: "t02",
               name: "Model View Controller",
               artist: "James Dempsey",
               album: "WWDC 2003"},
        t03: { id: "t03",
               name: "Four Thirty-Three",
               artist: "John Cage",
               album: "Woodstock 1952"}
      },
   playlists: { p01: { id: "p01",
                  name: "Coding Music",
                  tracks: ["t01", "t02"]
                },
           p02: { id: "p02",
                  name: "Other Playlist",
                  tracks: ["t03"]
                }
         }
 }

... I am seeking to display all playlists within the library with specific information:

p01: Coding Music - 2 tracks 
p02: Other Playlist - 1 tracks

Currently, the output of my code is:

 { id: 'p01', name: 'Coding Music', tracks: [ 't01', 't02' ] }
 { id: 'p02', name: 'Other Playlist', tracks: [ 't03' ] }

This is the current code snippet being used:

var keys = Object.keys(library.playlists);
for(var i = 0; i < keys.length; i++) {
  var key = keys[i];
  console.log(library.playlists[key]);
}

If you have suggestions on how to adjust this code for the desired output, please share. Thank you!

Answer №1

To extract data from an object and loop through it, you can utilize the Object.keys() method along with a forEach() loop.

var library = {"tracks":{"t01":{"id":"t01","name":"Code Monkey","artist":"Jonathan Coulton","album":"Thing a Week Three"},"t02":{"id":"t02","name":"Model View Controller","artist":"James Dempsey","album":"WWDC 2003"},"t03":{"id":"t03","name":"Four Thirty-Three","artist":"John Cage","album":"Woodstock 1952"}},"playlists":{"p01":{"id":"p01","name":"Coding Music","tracks":["t01","t02"]},"p02":{"id":"p02","name":"Other Playlist","tracks":["t03"]}}}

var playlists = library.playlists;
var result = Object.keys(playlists).forEach(function(key) {
  var playlist = playlists[key];
  var output = key + ': ' + playlist.name + ' - ' + playlist.tracks.length + ' tracks';
  console.log(output);
})

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

What is the best way to add an extension to specific specializations of a generic type?

Is it possible to create an extension for a generic type that conforms to a protocol, but is only valid for specific specializations of the generic type? Let's take for example a protocol that calculates the frequency of values within a type conformi ...

Trouble with the datepicker

I tried using the datepicker from and followed its demo, but unfortunately, the datepicker is not showing up on my page. I have gone through everything carefully, but I am unable to identify the reason behind this issue. Could someone please assist me i ...

Finding queries in MongoDB collections seem to be stalling

I have been attempting to create a search query to locate a user by their username. Here is the code: userRouter.get('/user/:user_username', function(req, res) { console.log("GET request to '/user/" + req.params.user_username + "'"); ...

AngularJS does not clear the array after a POST request is made

ISSUE Greetings! I am encountering an odd behavior with my backend. When I submit data, everything works flawlessly. However, if I press ENTER and submit an empty field, it reposts the previous value. Initially, I cannot submit an empty field, but after e ...

What happens to the parent scope in Javascript when declaring a subclass and why does it get overridden?

I have two classes in JavaScript, with one inheriting from the other. The structure is as follows: var Parent = (function(){ var self; var parent = function(){ self = this; self.type = 'Parent'; }; parent.protot ...

Repeatedly triggering the Jquery Dialog Event

When I open a calendar plugin in jquery dialog, I encounter a recurring issue. Every time I close and reopen the dialog, my calendar event onDayClick triggers multiple times – twice, thrice, and so on. <div id="show_calendar"> <div class="c ...

Tips for Creating an Upward-Dropping Dropdown Menu in HTML/JavaScript When Space is Limited on the Page

Hello, I am currently seeking a solution to adjust my dropdown menu so that it appears above instead of below when the page doesn't have enough space to display it fully. My tools for this project include HTML, Javascript, CSS, and JQuery exclusively. ...

The data type 'string' cannot be assigned to the type '(url: string) => string'.ts(2322)

I am working with a Material UI copyright component: export default function Copyright(link: string, text: string) { return ( <Typography variant="body2" color="textSecondary" align="center"> {'Copyright © '} <Link co ...

Angular custom filter with FabricJS

I am working with a binary/grayscale image and my objective is to filter the image so that all white color becomes transparent and all dark colors change to a specific user-defined color. I am facing challenges in creating a custom filter in Angular. I ha ...

Utilizing fibrous in node.js to efficiently fetch data from the request library

I am struggling to efficiently utilize the fibrous library in conjunction with request for obtaining the body of an HTTP request synchronously. However, I have encountered difficulties in managing the flow. In order to address this issue, I created a simp ...

Utilize information stored in a database to automatically navigate to a different webpage

I am currently working with PHP, HTML, and a mySQL database. Here are my current project requirements: Retreive specific data from the database and output it. Compare this data with predetermined values. If the data falls outside of the specified range, ...

Transferring a header across a series of interconnected services

I have a script that calls two services, combines their results, and displays them to the user. The services are: Service 1 (hello) and Service 2 (world), resulting in "Hello world". I want to include an ID in the headers to track the route of the calls. ...

Ajax dropdown menu displaying 'Loading Data' message during processing

Is it possible to display a Please wait.. or Loading... label underneath my Combo box while data is loading? I would like to show a Loading... message under the switch box when switching between Male and Female. https://i.sstatic.net/zpFDF.jpg This is th ...

Adjust the jQuery resizable handlers on the fly

I am encountering an issue when attempting to change the handler on a resizable element. Initially, I used : $(line) .draggable({containment:"parent"}) .resizable({ containment:"parent", handles: "e, w" }); N ...

What is the process for sending a JSON response and then redirecting to an HTML page after a successful event in Node.js using Express?

Trying to send a JSON response and redirect the page simultaneously in Express.js. Need help figuring out how to achieve this. Is it possible to redirect in Express.js while sending a JSON response to the client? The goal is to use this JSON data to render ...

Is there a way to set columns as initially hidden in MaterialTable?

I have a MaterialTable with many columns, and some of them are not always necessary to display. I am looking for a way to hide these columns unless the user specifically selects them. I attempted to use the hidden: true property in the column configuratio ...

Enhancing a popup with animated effects

I have been working on a popup that I want to add a subtle animation to. A fade effect seems like the perfect solution. Here is the code for the button: <a href="javascript:void(0)" onclick="document.getElementById('back_overlay').style.disp ...

There are various iterations of html2canvas available

After upgrading html2canvas from v0.5.0 to v1.0.0, a specific function ceased to work on iOS. Therefore, I am interested in utilizing v0.5.0 on iOS and v1.0.0 on other devices. Is there a way to incorporate and switch between both versions of html2canvas ...

Trouble shooting: Angular 2 Http get request not firing

I'm facing an issue where nothing happens when I try to subscribe to my observable. There are no errors in the console or during the build process. Below is the code snippet that I am using: My service getBlueCollars(): Observable<BlueCollar[]& ...

What is the best way to create an index for a user-provided value in a textbox

Looking for guidance on how to set an index to user-provided values in a textbox, append them to a table in a new row, and display that index in the first column of every row. I am unfamiliar with this type of functionality. $(document).ready(function() ...