What is the best way to cite the location of a nested object or array using a variable?

I am working with a dataset that includes objects and arrays within an object structure like this:

let productDataObj = {
  prodType1: {
    keyTermsArr: [],
    frequencyObj: {},
    ratingObj: {}
  },
  prodType2: {
    keyTermsArr: [],
    frequencyObj: {},
    ratingObj: {}
  }
};

As I am writing code to interact with these nested objects and arrays, I would like to store references to them as variables to avoid repetitive code. For example:

let keyTermsArrRef;
let frequencyRef;
let ratingRef;

for (let i = 0; i < products.length; i++) {
    if (prodType[i] == 1) {
        keyTermsArrRef = productDataObj.prodType1.keyTermsArr;
        frequencyRef = productDataObj.prodType1.frequencyObj;
        ratingRef = productDataObj.prodType1.ratingObj;
    }
    else if (prodType[i] == 2) {
        keyTermsArrRef = productDataObj.prodType2.keyTermsArr;
        frequencyRef = productDataObj.prodType2.frequencyObj;
        ratingRef = productDataObj.prodType2.ratingObj;
    }

    // Perform operations on keyTermsArrRef, frequencyRef, and ratingRef

The challenge I am facing is that the data is not actually stored in the nested arrays but only in the variables I created to reference them. Is there a way to use variables to point to the 'paths' of these nested arrays and objects?

Answer №1

Discussion on the topic of accessing dynamic properties using bracket notation:

for (let j = 0; j < items.length; j++) {
    // Utilizing dynamic property access to destructure object variables
    const {name, price, quantity} = itemDataObj[`itemType${itemTypes[j]}`]; 

Answer №2

Even though JavaScript doesn't have built-in support for storing references to nested objects and arrays, there's a clever workaround that can help you achieve the same effect:

One handy solution is to utilize Lodash's get Function.

import _ from 'lodash';

let keyTermsArrRef = _.get(productDataObj, `${productType}.keyTermsArr`);
keyTermsArrRef.push("additional terms");

Remember - other libraries like Ramda offer more advanced array and object manipulation capabilities as well.

Answer №3

One way to store the properties is by pushing them into an array. While not perfect, this method can be quite succinct:

const propertyList = []
for (const prop in productDataObject) {
  propertyList.push(prop)
}
for (let j = 0; j < propertyList.length; j++) {
    keyTermsArrayRef = productDataObject[propertyList[j]].keyTermsArray;
    frequencyReference = productDataObject[propertyList[j]].frequencyObject;
    ratingReference = productDataObject[propertyList[j]].ratingObject;
}

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

Troubleshooting the Vue.js component rendering issue

I am trying to display only one object from the data on firebase using [objectNumber]. I want to show {{ligler[1].name}} in the template, but it is causing errors: Error when rendering component Uncaught TypeError: Cannot read property 'name' o ...

When generating a docx file with html-docx-js, it lacks the capability to incorporate external CSS class styles into the document

I have been utilizing the html-docx-js module to convert html content into docx format. However, I am facing an issue where most of my CSS is externally loaded and html-docx-js does not apply any styles. Here is a simplified code sample: const html = &ap ...

What is the best way to retrieve the name of an element or component using JavaScript

I'm currently working on a webpage that includes ASP.NET panels and JavaScript which retrieves all components present on the page: var items = Sys.Application.getComponents(); My goal is to obtain the name/ID of each element stored in the 'item ...

Utilizing Redux-Form to Retrieve Input Values

When a radio button is clicked, I want to display a form using redux-form. I tried following a tutorial that uses checkboxes but couldn't figure out how to implement it with radio buttons. The tutorial link is selectingformvalues. I have 2 radio butt ...

Incorporating JavaScript for modifying Less files

Is it feasible to modify Less documents using JavaScript? I am attempting to adjust a property of a Less file with JavaScript. Here is my code: document.getElementsByClassName('content-main--inner').style.border = '1px solid yellow!importan ...

Tips for sending a PDF created with jsPDF as an attachment in an email using asp.net c#

I'm wondering if there's a way to attach a PDF file that was generated using jsPDF and email it in asp.net C#? This is the code snippet I have in c#: MailMessage message = new MailMessage(fromAddress, toAddress); message.Subject = subj ...

What is the process for transforming a pandas DataFrame consisting of lists of numbers into a 3D array?

I am facing a challenge with a pandas DataFrame that has the following structure: In [22]: df Out[22]: a b 0 [1, 2, 3] [4, 5, 6] 1 [7, 8, 9] [10, 11, 12] To create it, you can follow these steps: df = pd.DataFrame([[object() ...

There seems to be an issue with loading objects using the binary loader in three.js

I have been working on customizing the code of a three.js example to load a .js file that was originally in .obj format. I am using BinaryLoader.js to load the object, however, the object is not appearing in my modified code. Here is what my code looks lik ...

Is there a similar feature in jQuery to Prototype's Element.identify?

Are there any built-in jQuery methods or widely accepted default plugins that can automatically assign a unique ID to an element? Or is it necessary to create your own solution for this functionality? I'm seeking the jQuery equivalent of Prototype&apo ...

Set a maximum date limit for an input field of type "date"

Is there a way to set a limitation on the date selection so that users are unable to choose a date older than one year? I would prefer this restriction to be automatically compared to the system's current date. Any creative ideas are greatly appreciat ...

Conceal URL in <a> tag within View Page Source

As I develop a website, I have an href tag that looks like this: <a href="Folder1/Sample.pdf" target="_blank">xam study papers</a> This link is meant to open the PDF in a new tab. However, when viewing the website on Google Chrome and Ri ...

Is there a more efficient method to replace the element at arr[i] without using arr.splice() that is not timing

Having trouble with my solution and suspect that the .splice() function might be in the wrong place since I keep timing out. The issue: You have an array of integers. Each move allows you to increase one element by one. Find the minimum number of moves ...

Display data in an HTML table using PHP and AJAX within a single file

My project involves using PHP to populate an HTML table with random numbers upon page load. What I'm aiming to achieve is the ability to click a button and have the table populated with new numbers by invoking PHP through an ajax request. The challeng ...

Challenge with Superbox JS and Quicksand Combination

I am encountering an issue with my portfolio section. The Superbox () is working fine, but after clicking on a quicksand "filter" link, the superbox seems to be disabled. I need help fixing this. Below is the JavaScript code causing the problem. I suspect ...

How to update a ReactJS component based on changing values

As a user, I have a wishlist feature on my website. Whenever I add items to my wishlist, they are stored in the localStorage. I also want to display the total number of items in my wishlist automatically without having to refresh the page. Although the it ...

I keep receiving an error in Angular JS but I'm unsure of the reason

I've been working on AngularJS and created a basic module and controller. I'm attempting to show the data of an element inside the controller on the HTML view page, but all I see is {{student.name}} and I'm receiving an error message that sa ...

Can the store.dispatch method in Redux be considered synchronous or asynchronous?

This may seem like a simple question, but despite my efforts I couldn't locate the answer anywhere else. Can anyone clarify whether store.dispatch is synchronous or asynchronous in Redux ? If it is indeed asynchronous, is there a way to include a ca ...

Confusion Arises When Joomla Buttons Clash

I am facing an issue with two modules on my website, each containing a button code. The code for the buttons is as follows: First Button <div onclick="parent.location='first-link'" data-mce-onclick=""><button class="button">First Bu ...

What is the best way to modify a newly added element using jQuery?

When a user clicks a button on my screen, a new template is loaded dynamically using jQuery's .load() method. This transition adds new HTML to the page that was not present when the script initially loaded: (function($) { $('.go').on("c ...

Error encountered: The function 'showErrorMessage' is not exported from the file '../helpers/alerts'

Within the directory ../helpers/alerts, there is a file called alerts.js const displaySuccessMessage = (success) => { <div className="alert alert-success">{success}</div> } const displayErrorMessage = (error) => { <di ...