An array of length x containing keys of JavaScript objects

I'm currently working on a generator for chartjs to help me with creating datasets.

My approach involves using object keys to extract data from each element in an array.

Each element in the array may contain nested objects like this:

https://i.sstatic.net/IXl3D.png

This nesting poses a challenge because accessing specific data, such as the name of the object feedback_skill, requires multiple levels of key referencing:


data.forEach(function (x) {
    x['feedback_skill']['name']
});

This method isn't ideal for storing the accessed value in a single variable.

One alternative is to pass an array like this: serieKey = ['feedback', 'name'], where each element corresponds to a key in the nested structure to access the desired value.

However, these datasets can be complex with potentially endless layers. So my question is:

Is there a more efficient way to achieve this?

Answer №1

While native JavaScript may not have a built-in way to access deep properties from objects, there are various JavaScript frameworks that offer solutions for this. For instance, Dojo provides the lang.getObject method, and there is also a JQuery plugin and lodash functionality available for similar tasks. If these frameworks are not being utilized, creating a custom utility function could achieve the same result.

These utility functions typically allow you to specify the target property in "dot-notation", enabling calls like:

lang.getObject("feedback_skill.name", false, x)

Although the specifics may vary depending on the framework used, the overall concept remains consistent across them all.

Answer №2

Your approach seems solid and should be able to handle an unlimited number of layers effectively:

data.forEach(function(item) {
    for(index in seriesKey)
        item = item[seriesKey[index]]; // item will hold the desired value at the end of the loop
    performAction(item);
}

Just make sure that seriesKey is an array similar to the one in your example, containing all the necessary elements to reach the desired depth.

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

How can Array<T> in Typescript be used to dynamically determine and generate a new instance of T?

My challenge involves managing multiple typed Arrays containing different objects. I am searching for a way to create a function that can add a new blank object to any array, as long as the type has an empty constructor available. Being new to Angular 2 a ...

Tips for executing a JavaScript function within a secure sandbox environment

My current setup involves an application server developed in JavaScript (node.js) where I receive JS function code as input from a web browser. Now, my goal is to execute this function on the server without any interference with other processes. I am look ...

Sign up with identical username and email on WordPress

I'm currently facing a challenge with implementing http://jsfiddle.net/67BUG/2/ in wordpress registration, but I have experimented with various approaches without success. Within the wp-login.php file, you can find the code here - http://pastebin.com ...

Managing and enumerating array elements in an angular.js controller

In my Angular application, I am working with an array of objects that each contain a "ready" field storing a timestamp. My goal is to determine the count of objects where the "ready" timestamp is earlier than the current time. How can I achieve this? This ...

Issue with function not being triggered upon using the .click event

I am attempting to trigger a function on a click event using $(this) in order to catch the event and execute a function. Despite trying different methods, I continue to encounter an error flagged in Firebug: SyntaxError: missing ) after argument list I ...

Retrieve specific information using the identifier from the URL parameters during server-side rendering

I am trying to fetch data with a parameter from the URL using Nextjs. However, I am facing an issue where the parameter value is undefined. Here is the code snippet: const Room = () => { let fetchData; let roomId; const getID = () => { con ...

Make a hyperlink in Internet Explorer redirect to open in Mozilla Firefox

I am struggling with linking two URLs from a corporate intranet site built on Sharepoint to Firefox. The issue is that the links lead to an external site that doesn't function properly in Internet Explorer, which is the default browser for most users. ...

When using jQuery AJAX, the script is returning blank values

Facing a frustrating issue here. I'm sending an AJAX request to a PHP file, but when I check Chrome Network Tools, it doesn't return any JSON data. However, when I try posting the same data using POSTMAN in Chrome, it returns correctly. Also, if ...

Locate the nested route within one of the child components in React Router that corresponds to a specific id

Picture this scenario where I have a list of routes: const routes = [{ id: "1", path: "animals", children: [{ id: "1.1", path: "birds", children: [{ id: "1.1.1", path: "co ...

Unable to create the complete PDF file using html-pdf in a NodeJS environment

When trying to create a PDF from an HTML template, I am encountering some difficulties. While it works with static entries, I want to generate the PDF for multiple items that can vary each time. I feel like I might be overlooking something, so any suggesti ...

Using Ajax to send data from a parent JSP to a child JSP and then refresh the page

Can anyone assist me in resolving my issue? I'm attempting to incorporate an existing JSP partial (child) into another JSP page (parent). These pages are controlled by Java Controller classes in a Weblogic 12c environment using Spring. The child JSP i ...

The error message "Joomla! 2.5 and Virtuemart 2.0.18a - $.facebox is not recognized"

I encountered an issue while using Joomla! 2.5.8 and Virtuemart 2.0.18a where I received the error message "Typeerror $.facebox is undefined in vmprices.js (line 67)" when attempting to Add to Cart. Interestingly, switching back to the default Joomla! temp ...

JavaScript challenge at an electronics store coding competition

Hello, I recently attempted a code challenge but unfortunately only passed 9 out of the 16 tests. I am seeking feedback on what may be going wrong in my code. The problem link can be found here: function getMoneySpent(keyboards, drives, budget) { l ...

Parsing the JSON string from PHP using JSON.parse resulted in an unexpected and strange array

I've encountered a challenge when trying to transfer a JSON object from the server to client-side JavaScript. I fetched rows of data from a MySQL query and stored them in $result. Below is the code snippet: var json = '<?= json_encode($resu ...

The accordion seems to be stuck in the open position

Working on a website, I encountered a frustrating bug with an accordion feature. When clicking on the arrow, the accordion opens and closes smoothly. However, when attempting to close it by clicking on the title, the accordion bounces instead of closing p ...

Using Node.js to implement pagination with the POKEapi through a loop

Recently, I've been experimenting with the POKEapi to display information on 150 different pokemons. This is my first attempt at creating a node.js app as I'm just starting to learn javascript. The challenge I'm facing now is implementing ...

Using the PUT method in combination with express and sequelize

I am having trouble using the PUT method to update data based on req.params.id. My approach involves retrieving data by id, displaying it in a table format, allowing users to make changes, and then updating the database with the new values. Here is the co ...

Filtering Objects in Javascript: A Step-by-Step Guide

Consider an array containing various object details: Array [ Object { "deleted": null, "disabled": null, "id": "456", "price": 970, "size": Object { "br": 35, ...

Continuously decrease a sequence of identical numbers in an array through recursion

One of the key challenges was to condense an array of numbers (with consecutive duplicates) by combining neighboring duplicates: const sumClones = (numbers) => { if (Array.isArray(numbers)) { return numbers.reduce((acc, elem, i, arr) => { if ( ...

The event for 'deviceready' in Cordova is not getting triggered when placed inside the angular .run block

Recently, I've been facing difficulties in getting 'deviceready' to register within AngularJS. It was functioning properly earlier, so I'm puzzled about what might have altered. If I trigger 'deviceready' from a global addEve ...