Accessing elements of a multi-dimensional Javascript array: A step-by-step guide

In my Java script array, the structure goes up to 5 levels deep with elements containing strings and arrays.

photoList = 
    [Photographs, [
                    [2000, [
                             [London, [pic1.jpg, pic2.jpg, pic3.jpg]],
                             [Rome,   [p1.jpg, p2.jpg, p3.jpg....]]
                           ]],
                    [2001, [
                             [Berlin, [x1.jpg, x2.jpg,....]],
                             [Munich, [y1.jpg, y2.jpg, y3.jpg,...]],
                             [Frankfurt, [z1.jpg, z2.jpg]]
                           ]]
                  ]
    ];

Given an array "path" with index values that points to a specific photograph, for example, [1][0][1][2] corresponds to Year 2000 -> Rome -> p3.jpg. How can I access p3 using these index values?

I tried creating a string variable index="[1][0][1][2]" and attempted to access the element using photoList+index, but it didn't work. I also experimented with using a loop and slice method:

var elem = photoList;
for (var i=0; i<path.length; i++) {
  elem = elem.slice(path[i], path[i+1]);
}

If you have any insights or ideas on how to solve this problem, please share them. Your input is appreciated.

Answer №1

Have you considered using the following approach (assuming the path is an array of indexes, for example [1, 0, 1, 2]):

let element = photos;
for (let i=0; i<path.length; i++) {
  element = element[path[i]];
}

Answer №2

If you want to evaluate the combination of photoList and index, you can achieve that by converting photoList into a string before passing it to eval function. This will allow eval("photoList" + index) to work effectively.

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

Is there a way to verify that only the image was uploaded?

// why isn't this code working when I upload 1.chicken.jpg with a size of 180kb and 2.chicken.pdf, but only the chicken.pdf file gets inserted into the database? HttpFileCollection hfc = Request.Files; if (hfc != null) ...

Discover the benefits of utilizing router.back() cascade in Next/React and how to effectively bypass anchor links

Currently, I am working on developing my own blog website using Next.js and MD transcriptions. The issue I am facing involves anchor links. All the titles <h1> are being converted into anchor links through the use of the next Link component: <Link ...

Developing an SQL table for a website using JavaScript

My command is not functioning as expected and I am struggling to identify the issue. The database opens successfully, however, it fails to process the table creation. var createtable2 = 'CREATE TABLE IF NOT EXISTS offlineCabinDefects (id INTEGER PRIM ...

The problem with the Next.js 14 generateStaticParamsparams parameter is that it is currently

I'm using this documentation as a reference to extract parameters from the URL in my generateStaticParams function: https://nextjs.org/docs/app/api-reference/functions/generate-static-params#generate-params-from-the-bottom-up This is the route I am w ...

Using Firestore startAt() with Redux: a comparison of serializable and non-serializable scenarios

I find myself at a pivotal moment in my Firebase project and am seeking some general guidance. Here are the key points as I have gathered them through my research: When it comes to Firestore queries, there is a useful feature for pagination called startAt ...

Exploring how to use $lt and $gt in JavaScript with dates

I am attempting to retrieve data from a MongoDB collection. Below is an example of the data: { "entryDate" : "2012-10-14T00:00:00.000Z", "amount" : 1, "cardId" : "50786621e3b983f1078d0bc9", "_id" : ObjectId("507a17354c6cbd6a4b000001"), "addedDate" : "Sat ...

Ways to extract data from a JSON object

When using my web application, the Web API responds with the following JSON object: [ { "templateID":1, "template":"{\r\n \"Body\": \"sample date hete hee. Name\"\r\n}" }, { "templateI ...

Is it possible to attach the entered URL to an image following the text that has been inputted?

I've coded everything but the jquery part isn't working. Enter URL :<input type="text"> <button id="btn"> continue </button> <div contenteditable="true" id="bod"> Click here to start typing</div> $(document).ready( ...

Using the `map()` method in React's array

I stumbled upon an interesting example at http://codepen.io/lacker/pen/vXpAgj that closely resembles my current issue. Let's consider the following array: [ {category: 'Sporting Goods', price: '$49.99', stocked: true, name: &apo ...

The process of returning parameters from a modal view in Ionic

I am currently facing an issue with my modal view that is used for user login. I need to retrieve the user id from the modal and pass it back to the view behind. I attempted using $state.go but it was unsuccessful. Additionally, using ng-href would not wor ...

How can I use JavaScript to collapse a node list from Bootstrap 4.6.x using the .collapse('show') method?

I'm currently attempting to implement the Bootstrap method .collapse('show') on a node list of elements, but I've run into an issue in the console.log that reads: (Uncaught TypeError: findEl[i].collapse is not a function). Because I am ...

Using jQuery to target the td:nth-child selector inside a document.ready function is not viable

Currently, I am working on a language learning project where I import a table of German words and their English translations from a .csv file using the jQuery.csvToTable plugin. My goal is to replace the words in the cells with an HTML input when the lang ...

Designing architecture for NPM packages in TypeScript

I am currently developing multiple NPM packages using TypeScript and I am exploring the most effective strategies for supporting various target architectures. When compiling to ES3, there is extensive support but it comes with additional boilerplate for c ...

Ways to identify when the socket has been opened by the client?

When utilizing socket.io on the client browser side, is there a way to identify when the socket connection has been successfully opened? I am also interested in monitoring other standard messages such as errors and disconnections. In comparison to the Web ...

What is the best method to retrieve the window object in XUL?

I'm attempting to assign an onLoad event to the current webpage through a Firefox extension. My approach involves utilizing the gBrowser object, although I am uncertain if this is the most optimal method. The goal is to establish an onLoad event for t ...

Why are the values in my options created using the array map method empty in React?

I decided to use a for loop to generate an array containing the numbers 1 through 12 representing each month. I then attempted to utilize the map array method to create 12 options, but unfortunately they are coming up empty. Below is a snippet of the ...

Error Message: Undefined Service in Angular version 1.5.4

I'm currently developing a sample application using AngularJS 1.5.4, built on angular seed, EcmaScript 6, and with a node.js web server. For routing, I am following the guidelines provided here: https://docs.angularjs.org/guide/component-router. Howe ...

Real-time Updating of ChartJS Charts in Rails Using AJAX

I am currently working with Rails 5 and the latest version of ChartJS library (http://www.chartjs.org/docs/). My goal is to retrieve the most recent 20 items from the SensorReading model and update the Chart using setInterval and AJAX. I have successfull ...

"Enhancing user interaction with Vue.js through the stunning ripple effect on

Is there a way to customize the ripple effect from this source so that it doesn't always have to be a DIV? Here's an example: Currently, when I implement it like this: <ripple class="btn">send</ripple> It works as expected, but as ...

Why does my Redux callback keep getting invoked multiple times?

In developing a react application with redux, I have chosen to avoid using react-redux by manually handling all dispatched events. Below is a sample code snippet. The content of index.html <!DOCTYPE html> <html> <head> <script src=& ...