What are the best ways to combine, organize, and iterate through JavaScript objects?

When I run a loop, it returns a combination of integer values and objects as shown below:

2
{firstName:"John", lastName:"Doe", age:28, eyeColor:"blue"}
3
{firstName:"Jane", lastName:"Doe", age:22, eyeColor:"brown"}
1
{firstName:"Jack", lastName:"Doe", age:50, eyeColor:"red"}

These are unique values that the loop generates line by line. My goal is to iterate over the objects based on the numerical order and store each number and object in separate variables. The desired output is:

1
{firstName:"Jack", lastName:"Doe", age:50, eyeColor:"red"}
2
{firstName:"John", lastName:"Doe", age:28, eyeColor:"blue"}
3
{firstName:"Jane", lastName:"Doe", age:22, eyeColor:"brown"}

This structured data will enable me to effectively utilize a function like this:

loop sorted 
    some_function(number_variable, object_variable);
end loop

The specific order in which these values are called is vital for grid column reordering purposes.

I have attempted storing the objects in an array, but I am unsure how to sort them based on the accompanying number values.

Appreciate any assistance you can provide!

Answer №1

To create an array of objects based on numbers, use the formula index = number-1

var nums = [2,3,1];
var objects = [
{firstName:"John", lastName:"Doe", age:28, eyeColor:"blue"},
{firstName:"Jane", lastName:"Doe", age:22, eyeColor:"brown"},
{firstName:"Jack", lastName:"Doe", age:50, eyeColor:"red"}
];
var sortedObjects = nums.map(function(num) {return objects[num-1]});
sortedObjects.forEach(function(obj, i) {some_function(nums[i], obj)})

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

Modify the button's text with jQuery after it has been clicked

I've been struggling to update the text of a button after it's clicked, and I'm encountering an issue where it works in one part of my code but not in another. Could someone please guide me on what might be missing in my code? The first bl ...

What methods are most effective for showcasing Flash messages within Express.js?

I have a Node.js app in the EJS framework and I am new to JavaScript. Could someone please advise me on the correct way to set flash messages in Node.js? Below is my code which is throwing an error: C:\Users\sad\Desktop\Node Applica ...

Running javascript code after the completion of the render method in Reactjs

I am working with a ReactJS component: const com1 = React.createClass({ render: function() { return ( <a href='#'>This is a text</a> ); } }); I am looking to run some Javascript/jQuery code once the rendering ...

When trying to use bootstrap modal buttons, they do not trigger with just a single click when

In my Angular code, I have implemented validation logic for when $locationChangeStart is fired. When this event occurs, I need to call event.preventDefault() to stop it and display a Bootstrap modal. However, I am encountering an issue where I have to clic ...

Using Node.js to seamlessly read and upload files with Dropbox API

I am utilizing the Dropbox API to retrieve a file from the node.js file system and then transfer it into a designated Dropbox folder. The transfer process is successful, but the file ends up being empty, with a size of 0 bytes. var path = require("path") ...

Exploring Keypress events with Dojo's 'on' module

Recently, I've started utilizing Dojo's latest on module for event handling. It has been working well so far, but a new issue has cropped up. Specifically, when using the keypress event, I am unable to retrieve the character value (such as "2" or ...

Implementing the use of a partial view in ASP.NET MVC with the help of JavaScript

I am faced with a challenge of displaying 15 different partial views based on the user's selection from a menu tab. Essentially, I have these 15 menu tabs on one side of the page, and when a user clicks on a tab, the content related to that tab should ...

Is Babel necessary for enabling JavaScript compatibility in my TypeScript React project, excluding Create React App?

This is the webpack configuration for my React project built in TypeScript, module.exports = { mode: 'development', entry: ['./src/main.tsx'], module: { rules: [ { // Rule for ts/tsx files only, no rule for js/js ...

What is the optimal approach when incorporating images in HTML?

In the process of developing a Webapp, I am working with PHP and JS on the client side and utilizing MySQL on the backend. I am looking to store images when a new database record is added, such as a profile picture. What are the best practices for this s ...

Disappear gradually within the click event function

I have a coding dilemma that I can't seem to solve. My code displays a question when clicked and also shows the answer for a set period of time. Everything works perfectly fine without the fadeOut function in the code. However, as soon as I add the fa ...

Select objects from an array that are contained within another array of objects

I am dealing with an array of objects that contain various attributes such as weakness, id, and type. [ { weakness: [ "Fire", "Flying", "Ice", "Psychic" ], id: 1, type: [ "grass", "poison" ] }, ...

Using either Javascript or JQuery to update every cell in a particular column of a table

I need to use a button to add "OK" in the Status column of table tblItem, which is initially empty. How can I achieve this using JavaScript or JQuery? The table has an id of tblItem Id Item Price Status 1 A 15 2 B 20 3 C ...

Every individual child component must be assigned a distinct key prop, even if they are pre-defined. - Utilizing REACT

My navigation bar routes are sourced from a JSON file structured like this: { "categorias": [ { "nombre": "Teacher absences", "componentes": [ { "type": "url", ...

Encountering difficulties resolving the dependency tree while trying to install @react-navigation/[email protected]

After creating a new project called MyProject using react-native init MyProject, I opened it in VSCode and the first task was to install navigation. Initially, when running npm install @react-navigation/native @react-navigation/stack, it threw an error. S ...

Retrieve information using Observables just once in Angular 2

One of my Angular 2 components relies on a service that fetches customer data from a Web API and returns an Observable: getCustomers() { return this.http .get(this.baseURI + this.url) .map((r: Response) => { let a = r.jso ...

Injecting dynamic data into a function parameter with Angular 1 Interpolation

In my code, I have a feature that alters the text displayed on a button depending on certain conditions. $scope.text = 'Wait'; if(Number($scope.x) == Number($scope.y)) $scope.text = 'Go' else if(Number($scope.x) < Number($scope ...

The Javascript code fails to execute after other scripts have been employed

Trying to create an expanding search bar that expands upon button click and collapses when clicking elsewhere on the page. The issue I'm facing is that everything works well initially, but after the second script hides the input field on a click outsi ...

Is there a problem connecting to the MongoDB server?

I am having trouble connecting to the MongoDB server using the link provided below. I have double-checked the password and dbName, but it still won't connect. Can someone please assist me with this? const mongoose = require('mongoose'); ...

Adding a border to the <area> element: A step-by-step guide

Can a border be added around an <area> element? This would be useful for testing an imagemap, however the following code does not achieve the desired effect: area { outline: 1px solid red; border: 1px solid red; } ...

Can we include an option to display all pages in one row on a single page?

Is it possible to include an option to display all rows alongside the current options of 10, 15, and 100? I've been unable to locate this feature in the documentation: Check out the Codesandbox example: https://codesandbox.io/s/muidatatables-custom-t ...