A guide to locating an object using its key in JavaScript

There are many suggestions out there recommending looping through the object to find what you need, but I'm not convinced that this is the best approach in my situation.

Currently, I have an array with entries linking to another array called people (containing id and name) using person_id, as well as another array called projects (also containing id and name) using project_id.

What I require is the ability to access both the project and person with a specific id within the loop on entries, so I can retrieve their names. Following the suggestions of others would involve looping through both the people and projects arrays for each iteration of entries, which seems inefficient.

Therefore, I came up with the idea of creating what I call a "hashtable" from both the people and projects arrays during initialization. This involves creating new objects called people_hashtable and projects_hashtable, where the key is the id.

For example:

[
  {
    "id": "8",
    "name": "John Doe"
  }
]

would be transformed into:

{
    "8": {
        "name": "John Doe"
    }
}

This way, I can easily access the name without constantly looping through the arrays while still retaining the original order of the array (which is why I am not outputting it directly from the server like this; you can't quite order an object). I also use both people and projects in a selectbox that needs to be ordered by name.

Am I on the right track with this approach? Is there a better way to handle this? Or should I abandon this idea altogether and stick with the search loop suggested in other questions?

I aim to be as efficient as possible on both the server and client sides.

Answer №1

You essentially duplicated all the objects in order to bypass using a loop. However, unless there are severe performance issues, I recommend steering clear of that approach. If you absolutely require a form of hashmap, I suggest storing the index of the array instead of replicating the object:

// original array
var arr = [
  {
    "id": "8",
     "name": "John Doe"
  }
];

// lookup table
var lookup = {
  "8": 0
}

However, keep in mind that by doing this, any modifications made to the array will necessitate rebuilding the hashmap.

Creating it is rather straightforward:

var lookup = arr.reduce(function(lookup, item, index) {
  lookup[item.id] = index;
  return lookup;
}, {});

You can also utilize this method to create the object mentioned in your question:

var lookup = arr.reduce(function(lookup, item) {
  lookup[item.id] = {name: item.name};
  return lookup;
}, {});

Nevertheless, my suggestion would be to refrain from implementing this solution if possible.

Answer №2

Try using this code snippet for a possible solution. Check it out on JSFIDDLE

var data = [
  {
    "id": "8",
    "name": "John Doe"
  }
];

var object = {};
for(var x=0; x< data.length; x++){
   object[data[x].id] = {name: data[x].name};
}

console.log(object);

Answer №3

var itemsList= {
    "article1":{
         "id":"155",
         "name":"First Article",
         "value":-5199.6
    },
    "article2":{
         "id":"255",
         "name":"Second Article",
         "value":-424.91
    }
}

var articleIds = [];
for(var article in itemsList) {
    articleIds.push(itemsList[article]['id']);
}

console.log(articleIds);

Answer №4

This library https://github.com/paularmstrong/normalizr simplifies the process of data normalization and denormalization.

It can transform the following data structure:

{
  "id": "123",
  "author": {
    "id": "1",
    "name": "Paul"
  },
  "title": "My awesome blog post",
  "comments": [
    {
      "id": "324",
      "commenter": {
        "id": "2",
        "name": "Nicole"
      }
    }
  ]
}

into this output:

{
  result: "123",
  entities: {
    "articles": { 
      "123": { 
        id: "123",
        author: "1",
        title: "My awesome blog post",
        comments: [ "324" ]
      }
    },
    "users": {
      "1": { "id": "1", "name": "Paul" },
      "2": { "id": "2", "name": "Nicole" }
    },
    "comments": {
      "324": { id: "324", "commenter": "2" }
    }
  }
}

and vice versa.

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

Dropping challenging shapes in a block-matching game similar to Tetris

I'm currently working on a game similar to Tetris, but with a twist. Instead of removing just one line when it's full, I want to remove all connected pieces at once. However, I've run into a roadblock when trying to implement the hard-drop f ...

What could be causing the preloader to fail in my React application?

I am developing a React App with Redux functionality, and I am looking to implement a preloader when the user clicks on the "LoginIn" button. To achieve this, I have created a thunk function as follows: export const loginInWithEmail = (email, password) =&g ...

Transforming business entities into JSON format

Currently, I am facing a challenge with serializing my business objects into JSON for use in a JavaScript application. My main concern is maintaining the purity of my business objects by keeping them unaware of data access or persistence. Introducing a toJ ...

The search for the view in the directory "/views" was unsuccessful in Express 4.0

I've been working on a project using Express 4.0 and the Express3-handlebars libraries for NodeJS. Below is the setup: app.set('views', path.join(__dirname, 'views/')); app.engine('hbs', hbs({defaultLayout: 'main&a ...

Is there a way to switch the video source when a particular h3 tag is clicked?

https://i.sstatic.net/I2gIZ.jpgI'm currently working on building a video streaming site, but I've hit a roadblock. My challenge right now is figuring out how to make the episode selector change the video player's source. I'm a bit conf ...

Attempting to retrieve information from JSON or JSONP through the utilization of the WOT API

Recently, I utilized the WOT (web of trust) API and encountered a response structured like this: process( { "www.google.com": { "target": "google.com", "0": [ 95, 84 ], "1": [ 95, 84 ], "2": [ 95, 84 ], "4" ...

"Failure to update the $scope object within an AngularJS service results in no changes being reflected in

I am currently working on integrating Google maps into an Angular / IonicFramework project. The implementation involves a directive, a service, and a controller. Within the scope ($scope), I have objects for the map, marker, and geolocation. While the map ...

Can Firebase data be updated in real-time in a Vue app?

Utilizing Firebase for Authentication and integrating a database into a Vue app, my current task involves monitoring changes within a 'friends' collection specific to a user. The objective is to seamlessly display the list of friends while refle ...

JavaScript conditional calculation mechanism

Here is the code snippet I am referring to: function myFunction() { var x = document.getElementById("ins-feet").value; if(x >= 0 && x <= 1499) { document.getElementById("show-cost").innerHTML = "Cost: $" + 300; } else if ...

"Exploring Different Layouts in Mean.js: Whether on the Server Side or leveraging

I have been working on a mean.js application and I am currently trying to integrate an admin theme with the existing project. My query is: Is it possible to have multiple server layouts? For example, can we use layout-1 for regular users and layout-2 fo ...

Steps to trigger a modal form through an ajax call upon clicking a button

Here is the current code in "dir.php". The goal is to have the modal form appear after clicking the add button. Can you please review my code and provide a solution? Thank you! <a class="btn btn-primary btn-md btnAdd" role="button"><i class="fa f ...

prevent unauthorized changes to input using browser developer tools in Angular

We have a login page for our application with three fields: "user name," "password," and a "login" button. Here's the issue I'm facing: I enter a valid user name. Then, I open the Browser Developer Tools and input the following code: d ...

Preventing a webpage's CSS from affecting an iframe loading an HTML document

Whenever I load an iframe, it seems to change a bit. Do I need to apply some kind of reset or adjustment? How can I ensure that the content within the iframe looks consistent no matter what page it's loaded into? ...

Transfer a parameter from a user input to control pagination in React.js

I am working on implementing a simple pagination function in a React 16 project. My idea is to pass the button's value to the API query to retrieve the page number and navigate to the next pages. I am utilizing the Unsplash API for fetching images. I ...

Combining JSON data in Typescript using the merge method

Is there a way to effectively merge JSON objects in such a manner that simple values (strings, numbers, booleans, etc) get overridden when keys match, but when dealing with complex values (arrays and objects), different outcomes apply? 1.) For simple array ...

Transferring an object containing circular references from the server to client-side Javascript without losing its circular structure

Trying to send an object with circular references from a node.js server to client-side JavaScript is proving to be a challenge. On the server side (node.js): var obj = { circular: obj } //.... app.get('/', function(req, res){ res.render ...

I need assistance improving my poor JavaScript patterns and practices. Where should I turn for help?

After focusing primarily on back-end tasks for the past few years, it's become apparent to me that JavaScript (and CoffeeScript) projects have evolved significantly in my absence. Working mainly in a rails environment, my previous JavaScript/jQuery i ...

What is the best way to create a function that requires an argument in TypeScript?

I'm looking to bring in a module that requires an argument in Typescript. This is how it looks in javascript: const cors = require('cors')({origin: true}); // JS What would be the equivalent syntax in Typescript? ...

Deciphering WHERE conditions in a Node.js environment

Looking to convert the WHERE clause of a MySQL query into an expression for extracting data from a JSON file. For instance: `price`=8.95 AND `title`="The Lord price= AND of the Rings" The above example should transform into the following string after su ...

Connecting a pre-existing Angular 2 application to a Node.js server: A step-by-step guide

I am currently working on an Angular 2 application with the following structure : View Structure of my Angular app Furthermore, on the server side : View Structure of server app I have noticed that there are two module dependencies folders, but I am un ...