1

I have some JS objects and they each have a grandchild property called 'products'.

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

I would like to access the products array regardless of what the specific object out of the above it is.

Tried 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

How can I access the nested grandchild 'products' object regardless of the parents name?

Emma
  • 27,428
  • 11
  • 44
  • 69
Doug Fir
  • 19,971
  • 47
  • 169
  • 299
  • 1
    The regex that describe the above is: /ecommerce.[add|remove|detail|checkout|purchase].products/. But if you need to *access* - regex may not be sufficient since you have to *check* which pattern apply. – Mulli May 27 '19 at 01:23
  • 1
    Eventually more generic way: `Object.values(ecommerce).find(item => typeof item === 'object' && item !== null && !!item.products)` – bigless May 27 '19 at 01:30
  • Possible duplicate of [Dynamically access object property using variable](https://stackoverflow.com/questions/4244896/dynamically-access-object-property-using-variable) – Heretic Monkey May 27 '19 at 01:40

2 Answers2

2

You can simply loop through the ecom object and check for existence of following props detail','add','remove','checkout','purchase' on ecom object,

something like this

let outerKey = ['detail','add','remove','checkout','purchase']
let foundProducts = outerKey.reduce((op,inp) => {
      if(ecom[inp] && ecom[inp].products && ecom[inp].products.length){
      op.push(ecom[inp].products)
      }  
     return op
},[])

Tried using regex:

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

No this is not regex this is just logical OR, so you always end with ecom['checkout']['products']

Code Maniac
  • 37,143
  • 5
  • 39
  • 60
1

Let's say you have an object like that::

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 cannot pick up apples from whichever tree you happen upon - you will need to visit the trees and the branches that contain them...

The easiest and the most portable way would be to have a function that utilizes the following expression ::

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

and run error free.

Bekim Bacaj
  • 5,707
  • 2
  • 24
  • 26