Using Regular Expressions to access a deeply nested object

Within my JS objects, there is a common grandchild property called 'products'.

For example:

ecommerce.add.products, ecommerce.remove.products, ecommerce.detail.products, ecommerce.checkout.products, ecommerce.purchase.products

I am attempting to access the products array without specifying the specific object from the list above.

One method I tried involves using regex:

var ecomProducts = ecom[('detail'|'add'|'remove'|'checkout'|'purchase')]['products'];

TypeError: ecom[(((("detail" | "add") | "remove") | "checkout") | "purchase")] is undefined

var ecomProducts = ecom[/'detail'|'add'|'remove'|'checkout'|'purchase'/]['products'];

TypeError: ecom[/'detail'|'add'|'remove'|'checkout'|'purchase'/] is undefined

Is there a way to access the nested grandchild 'products' object regardless of the parent's name?

Answer №1

To iterate through the properties of the ecom object and check for the presence of

detail', 'add', 'remove', 'checkout', 'purchase'
on the ecom object, you can use the following approach:

Here is an example:

let keys = ['detail', 'add', 'remove', 'checkout', 'purchase'];
let foundProducts = keys.reduce((output, input) => {
      if(ecom[input] && ecom[input].products && ecom[input].products.length){
      output.push(ecom[input].products);
      }  
     return output;
}, []);

An attempt was made using regex:

var ecomProducts = ecom['detail']['products'] || ecom['add']['products'] || ecom['remove']['products'] || ecom['checkout']['products'] || ecom['purchase']['products'];

Note that this is not actually using regex but a logical OR operation, resulting in always selecting ecom['checkout']['products'].

Answer №2

Imagine having an object structured like this:

ecommerce = { 
   add: { products: ['add products'] },
   remove: { products: ['remove'] },
   detail: { products: ['prod details'] },
   checkout: { products: ['checkout'] },
   purchase: { products: ['purchase'] }
};

    for( var x in ecommerce )"products" in ecommerce[ x ] ? 
    console.log( ecommerce[ x ].products ) : 0;

You can't just pluck apples from any tree you see - you have to go to the right trees and branches where they are located...

The simplest and most versatile method would involve using a function that incorporates this expression:

for( var x in ecommerce )"products" in ecommerce[ x ] ? 
console.log( ecommerce[ x ].products ) : 0;

and it will execute without any errors.

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

Transferring information in React from a child component to its parent and then to another child

I'm currently developing my app using react.js and facing an issue with passing data between components. I have a Parent component (P) that needs to receive an array of objects from its child component (C1), then pass this data on to another child com ...

A guide on implementing array properties in Vue 3

Currently learning the fundamentals, I have an array set up in the parent component (App.vue) data() { return { fruits: [ "apple", "pear", "cherry" ], }; }, I'm aiming to have three instances of the s ...

Avoid re-running the onScroll function until completion

I have a unique idea for a slideshow where the slides fade in and out as the user scrolls up or down. The process involves detecting scroll movements and showing the next slide based on the direction of the scroll. The user scrolls using the scrollwheel ...

Removing a value from a JSON object by utilizing the .map function

My JSON object is structured as follows: [{"box":1,"parent":[],"child":[{"boxId":2},{"boxId":3}]},{"box":2,"parent":[{"boxId":1}],"child":[]}] I am attempting to remove the element "child":[{"boxId":2} with boxId=2 from the object. I have tried using a , ...

Using AngularJS Typeahead with restrictions on $http requests

I have been attempting to restrict the number of results displayed by Angular Bootstrap Typeahead during Async calls, but unfortunately, it does not seem to be functioning as expected. <input type="text" ng-model="asyncSelected" placeholder="Locations ...

combine the value of one key with the value of another key within an array

const array = [{ id: 1, name: 'Bob', education: [{ degree: 'bachelors', Major: 'computers' }, { degree: 'masters', Major: 'computers' }] }, { id: 2, n ...

loop through the array of objects using ng-repeat in Angular

I am facing an issue where I need to display the data fetched from a service in my application. The service response is as follows: Object {resultado:array[2], mensaje: "4 personas `necesita tu ayuda"} Currently, the "resultado" field contains an object ...

There seems to be an issue with the next-sitemap image location showing as undefined in the sitemap

I am having an issue with creating a sitemap in image:loc. When I view my xml in the browser, loc is showing as undefined. The goal is to display images present in blogs. Additionally, when I use console.log, the link displays in the terminal but shows as ...

Encountering a problem with PDF view in Next.js while using html2canvas and jsp

Currently, I am using html2canvas and jspdf with Next.js to generate a PDF. However, the generated PDF does not display correctly. The h1 tag appears similar to the p tag, which is not the desired outcome. I need assistance in fixing this issue. My goal is ...

Unable to associate Slider values with TextFields in MaterialUI

Currently, I am trying to create a slide with 2 markers to indicate a price range and interact with it on the slide. Although I have linked the input with the slider, the connection from the slider to the input is not functioning properly. My attempt was t ...

"Successful implementation of Ajax function in local environment but encountering issues when running online

I am facing an issue with my AJAX function. It works perfectly fine on my local server but does not return anything when I move it to my online server. Below is the code snippet: This is the part of the page where I call the showEspece() function: echo ...

Display arrays vertically within each column using PHP

I have an array with both rows and columns specified. My goal is to print each column as a list within a loop. $row = 3; $col = 4; $arr=[ '1' , '2' , '3' , '4', '5& ...

Exploring Angular scope variables using Jasmine while making an ajax request

Can anyone provide guidance on testing Angular scope variables in a controller that is created within an ajax request? Here's the setup: app.controller('NewQuestionCtrl', function ($scope, Question) { loadJsonAndSetScopeVariables($scope ...

Share a URL and display small previews from it - php

Have you ever noticed that on certain websites, such as Facebook, when you post a link it automatically displays thumbnails from the linked website? Like in the image below: Ever wondered how to achieve that effect? ...

Obtain the values from controls within the <td> element

I'm experiencing some difficulty creating an array of table cell values because the cells contain controls, not just plain text. $("#tbl_CGT tr").each(function() { var arrayOfThisRow = []; var tableData = $(this).find('td'); if (tab ...

Listening for time events with JQuery and controlling start/stop operations

I recently developed a jQuery plugin. var timer = $.timer(function() { refreshDashboard(); }); timer.set({ time : 10000, autostart : true }); The plugin triggers the refreshDashboard(); function every 10 seconds. Now, I need to halt the timer for ...

Maintain authentication state in React using express-session

Struggling to maintain API login session in my React e-commerce app. Initially logged in successfully, but facing a challenge upon page refresh as the state resets and I appear as not logged in on the client-side. However, attempting to log in again trigge ...

Angular 2 eliminates the need for nesting subscriptions

Is there a way to streamline nested subscriptions like the code snippet below? I want to extract values from the subscription for better organization, but using a global variable won't work because the subscription hasn't received the value yet. ...

React, facing the challenge of preserving stored data in localStorage while accounting for the impact of useEffect upon

Seeking some assistance with the useEffect() hook in my Taking Notes App. I've set up two separate useEffects to ensure data persistence: one for when the page first loads or refreshes, and another for when a new note is added. I've added some l ...

Tips for building forms with VUE?

Today is my first attempt at learning VUE, and I've decided to follow a tutorial on YouTube from freeCodeCamp.org. The tutorial covers the concept of components in VUE, specifically focusing on creating a login form project. Despite following the ins ...