Tips on accessing dictionaries with multiple values in JavaScript

I am struggling with a particular dictionary in my code:

{1:['a&b','b-c','c-d'],2:['e orf ','f-k-p','g']}

My goal is to print the key and values from this dictionary. However, the code I attempted didn't yield the desired results:

for (var key in dictionary) {
    // check if the property/key is defined in the object itself, not in parent
    if (dictionary.hasOwnProperty(key)) {           
        console.log(key, dictionary[key]);
    }
}

Instead of the expected output, I received some random numbers. How can I resolve this issue? This was the unexpected output I got:

key:34639values:mkey:34640values:akey:34641values:tkey:34642values:hkey:34643values:ekey:34644values:mkey:34645values:akey:34646values:tkey:34647values:ikey:34648values:ckey:34649values:skey:34650values: key:34651values:pkey:34652values:rkey:34653values:okey:34654values:bkey:34655values:lkey:34656values:ekey:34657values:mkey:34658values:

What I really want the output to look like is:

keys: 1,2
values: ['a&b','b-c','c-d'],['e orf ','f-k-p','g']

var dictionary = {1:['a','b','c'],2:['e','f','g']}
      for (var key in dictionary) {
          // check if the property/key is defined in the object itself, not in parent
          if (dictionary.hasOwnProperty(key)) { 
              console.log(`key: `, key);
              console.log(`values: `, dictionary[key]);
          }
      }

Edit: Furthermore, it turns out that the dictionary is actually being treated as string. How can I convert it back to a proper dictionary format?

Answer №1

To retrieve the keys of an object, you can use the following method:

Object.keys(dictionary)

This will return an array containing two elements: ["1", "2"].

Once you have the keys of the object, you can access its content using a simple for loop:

for(let key of Object.keys(dictionary))
    console.log(dictionary[key])

The output will be:

["a", "b", "c"]
["e", "f", "g"]

Additionally, remember to utilize console.table(dictionary) for displaying simple table structures effectively.

Answer №2

let myObj = {1:['apple','orange','banana'], 2:['pear','peach','plum']}
let myKeys = [];
let myValues = [];
for (let prop in myObj) {
    // checking if the property exists in the object itself and not in its prototype chain
    if (myObj.hasOwnProperty(prop)) {
        myKeys.push(prop);
        myValues.push(myObj[prop]);
    }
}

console.log(`keys: `, myKeys);
console.log(`values: `, myValues);

Answer №3

For those in need, I have devised a handy tool to meet your specific requirements.

let data = {1:['a&b','b-c','c-d'],2:['e orf ','f-k-p','g']}

const keys = Object.keys(data)
const values = Object.values(data)
console.log(`Keys: ${keys.join()}`)

let result = values.reduce((result, value) => { result.push(JSON.stringify(value)); return result}, []).join()
console.log(`Values: ${result}`)

I trust this solution will be of assistance.

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

Unable to properly execute object calls with promises

I was facing a challenge with my code where I wanted to return two values in my promise chain, but was only able to call one of them successfully. Here is the section of my code causing the issue: app.get('/projects', (req, res) => { practic ...

Express route encountered an error with an undefined value

Here's the method declaration: exports.postRedisValue = function(req,res) { let keyRedis = req.body.key; let valueRedis = req.body.value; console.log(keyRedis); //displays as undefined if(keyRedis && valueRedis){ ...

Passing a parameter from a redirect function to an onClick in React using TypeScript

I am facing a challenge in passing a parameter to my redirectSingleLocker function. This function is intended to take me to the detailed page of a specific locker, identified by a guid. The lockerData.map method is used to display all the JSON data in a ta ...

JavaScript conversion of arrays to JSON data structures

Here is the code snippet along with the variable 'polygon': var directionsDisplay; var directionsService = new google.maps.DirectionsService(); var map; var bermudaTriangle; var directionsPoints; var example; var rez; function initialize() { ...

The TextView is not displaying the Android Json data retrieved from mysqli

Currently, I am conducting a basic test to display JSON data fetched from PHP MySQLi in a TextView. TextView mTxtDisplay; String url = "http://192.168.1.102/web_service/test.php/"; @Override protected void onCreate(Bundle savedInstanceState) { super ...

What is the best way to retrieve a MariaDB query result using Node.js?

I've been delving into the world of Node.js to enhance my web development skills, particularly in retrieving data from a mariaDB using SELECT queries and converting it into JSON for client requests. Despite scouring the internet and stackoverflow, I h ...

It appears that the JSON format of the HTTP response body returned by Rails is not valid

Currently, in my Rails project, I am utilizing the following method to return a JSON response: def return_json render json: params end Upon inspecting the response using Chrome Developer Tools, everything appears to be correct. However, upon examinin ...

The operation in Mongo DB carried out a $pull to eliminate the ObjectId("... id") from the nested sub-array

I've scoured every nook and cranny of the internet in an attempt to resolve this issue, but so far I've come up empty-handed. My goal is to use the mongodb $pull function to remove an Object from an array nested inside a Schema. I've success ...

Can you transform text with accents into plain ASCII characters?

I am seeking a solution in Javascript to convert accented letters and various encodings into plain English ASCII characters. The goal is to achieve the following transformations: éclair ~becomes~ eclair bär ~becomes~ bar привет ~becomes~ privet ...

Tips for calculating the distance from the cursor position to the visible area

Is there a way to determine the cursor's offset from the top of a textarea's view rather than its position? While e.target.selectionStart provides the cursor position, $el.scrollTop gives the scroll offset of the textarea. Any suggestions on ho ...

AppleScript: Check if the value of document.getElementById is empty, then fill in the value

Hello everyone, it's my first time asking a question here. I have an AppleScript that takes values from a Numbers document and fills them into different fields of a webform using document.getElementById. Everything is working perfectly so far, but now ...

Tips for dynamically adjusting an iframe's content size as the browser window is resized

Currently, I am in the process of building a website that will showcase a location on a map (not Google Maps). To achieve this, I have utilized an iframe to contain the map and my goal is for the map to adjust its width based on the width of the browser wi ...

Adding JSON data to a table with the keys in the first row is a simple process that can be achieved

Previously, I have created tables with XML formatted results and JSON data in the "key: data" format. To access the data, I would use syntax like results.heading1 and then map the data into a table by matching the key with the data. Now, a new client is o ...

Maintain the spacing of an element when utilizing *ngFor

Using Angular.js and *ngFor to loop over an array and display the values. The goal is to preserve the spaces of elements in the array: string arr1 = [" Welcome Angular ", "Line1", "Line2", " Done "] The ...

What is causing the newly generated input tags to disappear from the page?

I'm having an issue where my code successfully creates new input tags based on user input, but they disappear shortly after being generated. What could be causing this to happen? <form> <input type='text' id='input' /> ...

Error: Unable to call topFrame.window.changeSelectedBarStyle because it is not a valid function. What could be causing this

This function is called changeSelectedBarStyle: function changeSelectedBarStyle(tdId){ $("#menuTable td").each(function(index){ if(this.id == tdId){ $(this).removeClass("menuPanel"); $(this).addClass("menuPanelSelected" ...

Comparing Nodes Armed with Clusters to Nodes Sporting Threads

Can you explain the key distinctions between node cluster and Threads agogo, including their respective advantages and disadvantages? From my understanding, Threads agogo creates a background thread while node cluster initiates a new process to run in th ...

Retrieving a list of numbers separated by commas from an array

Currently, I'm retrieving data from a MYSQL database by executing the following SQL command: SELECT GROUP_CONCAT(MemberMemberId SEPARATOR ',') AS MemberMemberId FROM member_events WHERE event_date = "2000-01-01" AND Eve ...

Trouble with integrating HTML5 canvas from an external JavaScript file

Having trouble with storing canvas js in an external file. If the javascript responsible for drawing on the canvas is included in the html header, then the rectangle is displayed correctly. Here is the working html (javascript in html header): <!DOCT ...

JavaScript making a request to a web service

When trying to call a webservice in a JavaScript file using JSON, the web service is only accessible if both the .asmx file and JavaScript file are located on the local server or if they are both uploaded onto the live server. However, I am looking for a ...