What is the best way to establish a new JavaScript data type that can be accessed using both key and index?

Looking to create a unique datatype or object in JavaScript that allows access by both index and key, as well as having a length property to display the number of items in the datatype. Something along the lines of:


MyDataType[0].name="John"
MyDataType[0].salary="over 1k"

If I were to write:

MyDataType['John'].salary //I should get "over 1k"

And also if I were to write:

MyDataType[0].salary //I should also get "over 1k"

I would like it to include:

MyDataType.length //should return 1

Is this achievable?

I experimented with Proxy and it worked smoothly for the index/key aspect but lacked a length property. When using an array, I had access to index and length properties but couldn't use keys.

Appreciate any guidance you can provide. Thank you!

Answer №1

If you are facing challenges similar to what I experienced, I have finally discovered a solution thanks to @Quickredfox at this link:

Here is the code snippet that helped me:

"use strict";
 var MyCollection = new Proxy(
[{
name: 'monkey',
 score: 50
}, {
    name: 'giraffe',
 score: 100
}, {
name: 'pelican',
score: 150
}, {
    name: 'ZZoo',
  score: 69
}], {
 get: function(obj, prop) {
  if (prop in obj) {
    // default behavior
    return obj[prop];
  }
  if (typeof prop == 'string') {

      if (prop == 'length') {
      return obj.sort(function(a, b) {
        return obj.length;
      });
    }    

   for (var i = 0; i < obj.length; i++) {
      var player = obj[i];
      if (player.name == prop) {
        return player;
      }
    }

    return;
  }

}
});

document.write(MyCollection.length);

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

Passing events value in Fullcalendar Plugin by utilizing a javascript function to format events in the Fullcalendar event format

Currently, I am utilizing the full calendar plugin to display data on a calendar from a workflow. The values needed for the events are obtained in a separate function and need to be passed as fullcalendar events. I am uncertain about how to retrieve these ...

Show dynamic outcomes on the site

I'm currently in the process of building a website for a travel search engine and I'm interested in displaying the results in a similar manner to what is done on Hipmunk. Here are some key details: The website is being developed using Django. ...

Using JavaScript's FOR loop in combination with AJAX

I'm encountering an issue with using AJAX and a FOR loop. Within my PHP file, there are several if statements that return different prices based on a number range (1-9). For example: 1 -> echo "15.20"; 2 -> echo "11.10"; 3 -> echo "13.65"; ...

Exploring Nodejs and delving into fundamental queries

As I delved into the world of Nodejs, I quickly realized that my knowledge was limited to just being a user. Transitioning to creating my own server posed challenges that were not easily resolved by online tutorials. This led me here seeking guidance to tr ...

When implementing AngularJS in a situation where the page layout is created by the user, what is the best

As I work on developing a web application, my main goal is to incorporate around 6 unique "widgets" that users can interact with. These widgets will serve different functions and users will have the ability to add, remove, and position them as they wish on ...

Angular $resource failing to transfer parameter to Express endpoint

I am currently working on an Angular application that needs to retrieve data from a MongoDB collection. To accomplish this, I am utilizing the $resource service within the flConstruct. The "query" function works well as it returns all data from the server ...

Guide on removing the parent JSON array while retaining the child JSON array

I have been searching for a solution to remove specific JSON array elements, but I have not found one yet. Here is the JSON data I am working with: [ { "KODE": [ { "name": "kode", "value": [ ...

Enhancing jqgrid by incorporating cellattr to JSON colmodel

I've been experimenting with adding a custom cellattr function to my colmodel JSON response, but I'm having trouble getting it to work. I've tried applying classes and styles without success, so now I'm attempting to debug by logging so ...

Error message: The recursive function is unable to return a value when operating

My current task involves solving this problem recursively: Clean the room function: given an input of [1,2,4,591,392,391,2,5,10,2,1,1,1,20,20], create a function that organizes these into individual arrays that are ordered. For example, answer(ArrayFromAb ...

The 'props.p' navigation in react-native is undefined

I have gone through various forums and discussions regarding this issue, but none of the solutions seem to work for me. For some reason, I am facing difficulties passing props to react-navigation when I attempt to navigate, resulting in the following erro ...

Unable to trigger onClick event

The button I have with the id "jump-button" is not functioning at all. When clicked, nothing happens. I have added an alert(); to the onclick attribute to test if the button is working. However, the other two buttons (next and prev) are working perfectly ...

Converting Typescript objects containing arrays into a single array

Looking for some assistance with this problem :) I am trying to convert the object into an array with the following expected result: result = [ { id: 'test-1', message: 'test#1.1' }, { id: 'test-1', mess ...

Cypress and VueJS: How to target elements that are dynamically generated following a specific user interaction

I am currently testing a new feature where a button will only appear for the user to click after they have completed another action. Before proceeding with the action, I am verifying if the button exists: cy.get('span') .contains('Selec ...

Move the DIV element to a static section within the DOM

In my Vue app, I have implemented methods to dynamically move a DIV called 'toolbox' to different sections of the DOM. Currently, the DIV is positioned on the bottom right of the screen and remains static even when scrolling. My goal is to use t ...

Ways to implement a custom scrollbar across an entire webpage:

I am trying to implement the Jquery custom content scroller on my webpage to replace the default scrollbar. However, I am facing difficulties in getting it to work properly. You can view my code on Codepen. Although the plugin works fine with smaller blo ...

Encountering an issue while trying to import the D3.js library into my React.js application

I'm having trouble with properly importing the d3.js libraries in my react.js app. I am using import * as d3 from 'd3' to import everything and store it in the d3 namespace, but I keep getting an error that says - Cannot read property ' ...

Incorporating Numerous Location Pointers in Angular-google-maps

I've been struggling to show multiple map markers in my Angular project. I have a service called retsAPI that queries a local MLS database for home listings, and I'm attempting to display these items on a Google map. Below is my controller code. ...

Can other JavaScript event listeners be synchronized with an asynchronous event?

My goal is to manipulate a web page using Tampermonkey where there is a button with certain event listeners followed by a redirect. Is it possible for me to insert my own click event handler into the button, which triggers an AJAX request and waits for it ...

Tips for populating individual arrays in AngularJS with data from a JSON:- Iterate through the JSON

I am attempting to extract each data from a JSON file and store it in a new array, as I want to create a graph. However, the process is not working as expected. Here is what I expect: f = { "FAKULTAS":"01/FKIP", "FAKULTAS":"02/FMIPA", "FAKULT ...

Is it possible for me to hand over control to a child process and retrieve the result in Node.js?

Recently, I encountered an issue where multiple simultaneous GET requests to my Node.js server caused it to become overwhelmed and unresponsive, leading to timeouts for clients (503, service unavailable). Upon thorough performance analysis, I discovered t ...