Retrieving values of objects based on array keys

Hey everyone,

I have a question that might seem silly, but I'm feeling stuck and could use some assistance.

So, I have two sets of data - one is an object structured like this:

var userData = {
  "2_6": {
    "name":"John Doe",
    "location":"New York"
  },
  "2_70": {
    "name":"Jane Smith",
    "location":"Los Angeles"
  },
  "2_59": {
    "name":"Michael Johnson",
    "location":"Chicago"
  }

And the other set is an array representing a specific order:

var userOrder = ["2_70", "2_59", "2_6"];

My problem arises when I try to log the names from the userData in the order specified by userOrder using jQuery. Here's what I have so far:

 $.each(userOrder, function(key)
{
    console.log(userData[key].name);
}

In theory, this should output the names from the userData based on the userOrder sequence, but unfortunately it's not working as expected. Any suggestions or tips would be greatly appreciated! Thank you!

Answer №1

k within the jquery each function represents the index, not the actual key itself.

var pwData = {
  "2_6": {
    "name": "ggregreg",
    "location": "Manchester",
  },
  "2_70": {
    "name": "rwerwer",
    "location": "Solihull"
  },
  "2_59": {
    "name": "Amy",
    "location": "yjhtgeg"
  }
};
var pwOrder = ["2_70", "2_59", "2_6"];

$.each(pwOrder, function(index, key) {
  console.log(pwData[key].name);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Jquery is not necessary for this task, as it can be achieved using pure javascript

var pwData = {
  "2_6": {
    "name": "ggregreg",
    "location": "Manchester",
  },
  "2_70": {
    "name": "rwerwer",
    "location": "Solihull"
  },
  "2_59": {
    "name": "Amy",
    "location": "yjhtgeg"
  }
};
var pwOrder = ["2_70", "2_59", "2_6"];

pwOrder.forEach(function(key) {
  console.log(pwData[key].name);
});

Answer №2

James is spot on.

When looping through pwOrder, the code iterates over each element in the array and prints out the corresponding name from pwData.

Success.

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

Understanding the operational aspects of Typescript's target and lib settings

When the tsconfig.json file is configured like this: "target": "es5", "lib": [ "es6", "dom", "es2017" ] It appears that es2017 features are not being converted to es5. For example, code like the following will fail in IE11: var foo = [1, 2, 3].includes( ...

Difficulty encountered while integrating chart.js with Django using npm

Encountering an issue while using Chart.js in my Django project - when utilizing the NPM package, it fails to work. However, switching to the CDN resolves the problem seamlessly. Chart.js version 3.9.1 Below is a snippet from my project's index.html ...

Make the div disappear upon clicking the back button in the browser

When a user selects a thumbnail, it triggers the opening of a div that expands to cover the entire screen. Simultaneously, both the title and URL of the document are modified. $('.view-overlay').show(); $('html,body').css("overflow","h ...

Experiencing difficulties applying a condition in a mongoDB projection

Imagine a scenario where I have a separate collection named 'Collection1' containing the following data: userID: "1" container:[ {"item" : "false", "price" : NumberDecimal("80"), "sizes" : "S", "arrayIndex" : NumberLong(0) } {"item" : ...

PHP: combine two multi-dimensional arrays without merging the levels of depth

Two arrays are available: print_r($array_one): Array ( [a] => Array ( [param1] => 1 [param2] => 2 ) [b] => Array ( [param1] => 3 [param2] => 4 ) ) print_r($array_two): Array ( ...

Is it possible to organize elements in a given array based on their data type?

I am working on a script to determine the data type of each value in an array by using foreach() and var_dump(). Here is an example array that I am working with: $arr = ['this','is', 1, 'array', 'for', 1, 'exa ...

Leveraging the navigator geolocation feature in tandem with reactors

Struggling to save geolocation variables position.coords.lat/long in a global scope. Check out this code: var GeoLoco = React.createClass({ lat: 0, long: 0, handler: function(position) { ...

What is the method for assigning a value to a variable in xhr.setRequestHeader?

I'm working on setting a value to the variable in xhr.setRequestHeader(Authentication, "Bearer" + parameter); with xmlhttprequest. Can you provide guidance on how to effectively pass a value to the variable within xhr.setRequestHeader? ...

Using Javascript to link object-oriented programming methods to events and better understand the 'this' keyword

I am currently learning OOP Javascript but struggling with understanding the this keyword and working with events. My goal is to bind a common event to multiple DOM objects while storing data about these objects in a global container for better performanc ...

Modifying button appearance upon clicking using JavaScript

JavaScript: const buttons = document.getElementsByClassName("togglebtn"); for (let i = 0; i < buttons.length; i++) { buttons[i].onclick = function () { this.classList.toggle("active"); } } html: <md-butt ...

what is the best method to schedule tasks at a specific time in node-schedule?

I am facing an issue with running a node task daily at 8AM using the node-schedule package https://www.npmjs.com/package/node-schedule. Instead of running every day at 8AM, it is currently running every minute. What method should I use to correctly configu ...

Looping through a JSON object with nested structures in PHP in order to locate

My goal is to iterate through nested JSON data in search of a specific name containing a particular string and then extract the associated value. Specifically, I am looking for a name string of "myKey" with the corresponding value string as "12345678". De ...

I'm facing an issue in React where using onChange is causing all DOM elements to be cleared. The input form functions correctly when used with a button, but for some reason, the onChange event does not

Currently, I'm working on a grid that can be resized using two input fields in the application. The setup involves an input for cells across, an input for cells down, and a button to set the grid, which is functioning well. However, I would like to ma ...

I keep getting double results from the Multiple Checkbox Filter

Currently, I am facing an issue with a checkbox filter on a product page that I'm developing. The filter is functioning correctly, but I encounter duplicate results when an item matches multiple criteria. For instance, if I select both 'Size 1&ap ...

Experiencing difficulty with the toggle menu on an HTML/CSS website. Unable to access the menu when hovering over the hamburger icon on the right side

I am experiencing an issue with the toggle button in the menu when the screen size is max-width = 1200px. Specifically, when I toggle the button, nothing appears. Can someone please assist me? I have included Bootstrap 4.3 in my HTML script. The menu that ...

Unable to store the user's input information in the database

I've been attempting to incorporate an "add" button feature that saves/adds/inserts data into my table. I have inputted some text in the form of tags (input type), but unfortunately, it doesn't seem to be functioning properly. Despite conducting ...

Generating JSON data with Ruby for a collection of items

I'm a beginner with Ruby. My goal is to generate a JSON file for a set of elements. To achieve this, I am utilizing the each function to fetch the data. The desired structure of the JSON file for a 4 element array is as follows: '{ "desc" ...

Display progress bar dialogue upon submission

I am looking to implement a jQuery popup that displays "Loading..." on every postback. I am unsure of how to achieve this and which technologies to use. My goal is to create the code in a superclass so that it only needs to be coded once. Ideally, when I c ...

A function that retrieves an array containing each individual element from a multi-dimensional array

In my system, I have two essential objects: Order and ProductOrder. Order Object: { id:number; productOrders: ProductOrder[]; } ProductOrder object: { id: number; productName: string; } Currently, I store an array of Order objects in a variable called o ...

Transforming a unirest 'GET' call into an axios request

I am currently utilizing TheRundown API to access sports data. The example provided to me makes use of unirest, but I am endeavoring to adapt that example into an axios request. While I have managed to make it work for the most part, my main challenge lies ...