AngularJS Tutorial: Storing the Index Position of a JSON Object without Saving the Object Itself

My JSON data is as follows:

$scope.myjson = [
                   {id: "1", name: "a"},
                   {id: "2", name: "b"},
                   {id: "3", name: "c", children: [{id: "4", name: "d"}]}
               ];

I am looking to store the position of object X in JavaScript, such as the first object at $scope.myjson[0], without saving the actual object itself. Similarly, I want to save $scope.myjson[2].children[0].

Should I save it as a string? How can I retrieve that object in O(1) time once saved?

Answer №1

What is the benefit of saving the position of an object rather than the object itself?

If you want to store objects based on an id for quick retrieval, you can use a method like the one suggested below (not tested):

var find = (function() {
    var cache = {}, fn; 

    return fn = function(/*array*/ arr, id) {
       if(cache[id]) return cache[id];
       for(var i=0; i < arr.length; i++) {
          if(arr[i].id === id) 
             return (cache[id] = arr[i]);
          if(arr[i].children && val = fn(arr[i].children, id)) 
             return (cache[id] = val);
       }

       return null;
    }
})();

This method allows subsequent calls to find to fetch the cached object quickly. Depending on the array size and lookup frequency, iterating over it once to create a hash map of id => object could also be efficient.

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

Converting to alphanumeric characters using JavaScript

Is there a way to efficiently encode a random string into an alphanumeric-only string in JavaScript / NodeJS while still being able to decode it back to the original input? Any suggestion on the best approach for this would be greatly appreciated! ...

Guide on integrating a jQuery method for validating a value using regular expressions

I'm currently using the Jquery validation plugin to validate form fields. One of the fields I am validating is for academic years, which should be in the format of 2013-2014. To achieve this validation, I have created a custom Jquery method as shown b ...

Issue with API delivering zip file - Headers cannot be modified after being sent to the client

I've encountered a problem with my API that generates a zip file using the archiver module and sends it back as a response to be downloaded on the client side. Whenever I attempt to send the zip file back, I receive the error Error [ERR_HTTP_HEADERS_S ...

Error: Unexpected character 'o' encountered in AngularJS syntax

Whenever I try to call this controller, it gives me an error. hiren.controller('hirenz' , function($scope , $http , $location , $routeParams){ $http.post((rootURL + "music") , {'alpha' : $routeParams.alpha , 'name' : $rou ...

Error encountered during file download with AXIOS: TypeError - 'validateStatus' in blob cannot be searched using 'in' operator

I recently encountered an issue with a Vue app when attempting to download a CSV file using Axios, and I am unsure of how to resolve it. downloadFile: function(res = "") { axios .get('/api/file/' + res, 'blob') ...

Encountering difficulties in compiling Dynamic HTML with the $compile function

I'm attempting to incorporate dynamic HTML into my code with the following lines: var el = $compile('<a ng-controller=\"tableController\" ng-click=\"open\">...ReadMore</a>')($scope); But I'm encounterin ...

Why Next.js and MongoDB (minus Mongoose) is giving back an empty array

I am currently learning how to use API routes in Next.js with sample data retrieved from MongoDB. My challenge lies in attempting to retrieve data from a single object, which is proving more difficult than expected as I am new to working with MongoDB. Aft ...

Automatically navigate to the bottom of the page by applying the overflow auto feature

I've been working on a chat application using Vue.js. I have set the overflow property to auto for my div element. My goal is to automatically scroll to the bottom of the div so that users won't have to manually click the scrollbar to view the la ...

jQuery Mobile persists in loading the initial page of a multi-page document after form submission

After searching extensively for an alternative to data-ajax="false" without success, I've found myself in a dilemma. In my Phonegap application, utilizing jQuery Mobile to submit a form requires running it through the standard submit function in jQuer ...

The equation of jquery plus ie7 results in an undefined value

I am experiencing a strange issue in IE7 with a jQuery script. This problem seems to only occur in IE7. In summary, when I check the console window, it shows that jQuery is not defined - even though I have loaded jQuery (version 1.7.1) from my disk and can ...

How can I efficiently utilize HTML/CSS/JS to float items and create a grid that accommodates expandable items while minimizing wasted space?

After meticulously configuring a basic grid of divs using float, I've encountered an issue. When expanding an item in the right-hand column, the layout shifts awkwardly. My goal is to have boxes A and B seamlessly move up to fill the empty space, whi ...

Having issues with passing POST data during file handling operations

I am attempting to utilize Ajax POST on my WordPress website to check if checkboxes are selected and update their values in the database upon clicking a button. Although using the standard PHP form submission is the simplest method, the fields that I need ...

Error message in development mode: Next.js Unhandled Runtime Error "Failed to load script: /_next/static/chunks/..."

I have a next.js app... running in dev mode. One of the pages maps through JSON data from the backend and displays an 'EventListItem' component for each 'event' object. List page: http://localhost:3000/6/events/2021-08-26 (http://loca ...

Refresh two angular-datatables

I'm facing a challenge when it comes to updating two datatables simultaneously on the same page. Here's how my HTML is structured: <table id="datatable1" ng-if="Ctrl.dtOptions1" datatable="" dt-options="Ctrl.dtOptions1" dt-column-defs="Ctrl. ...

Discover the initial or subsequent location of a specific value within an array

Is there a way in SAS to search for a specific value in an array, similar to using the index() or find() functions? For instance, if you want to find the value of 11 in an array named arr, starting from the first position in the array, you can use code li ...

I am setting up two data picker fields: the first one should display the date as 01/01/2022, while the second field should show today's date

https://i.sstatic.net/jsTme.png In my project, I am working on setting up 2 input date fields: 1.1. The first field is for the start date and it should automatically display as: 01/01/current-year(For example, if the current year is 2022, then it would sh ...

Error occurs when contacting ASP.NET Web API from AngularJS

I am facing an issue in my AngularJS web application which uses ASP.NET Web API as its backend. Whenever I try to call the Web API service, I encounter an exception. Here is an example of the code: Angular: $http.get('api/notes/').success(functi ...

Combining Two JSON Arrays Featuring Unique Keys

I have two JSON arrays with slightly different keys. The first JSON array contains the keys id, name, and title. The second JSON array includes id, title, forename, name, and company. I am wondering if it's possible to merge these two arrays so th ...

Master your code with Rxjs optimization

Looking at a block of code: if (this.organization) { this.orgService.updateOrganization(this.createOrganizationForm.value).subscribe(() => { this.alertify.success(`Organization ${this.organization.name} was updated`); this.dialogRef.close(true ...

Vue's reactivity in Vue 3 is exhibiting strange behavior with boolean data

Currently, I am attempting to modify a boolean variable. Upon the initial page load, everything works as expected. However, upon reloading the page, the variable gets updated locally within the method but not in the global data section. As a result, an err ...