-3

I haw the two following variables:

'ecommerce': { 'checkout': { 'actionField': {'step': 4}, 'products': [{
'name': 'Spirit Pack', 'id': '12345', 'price': '55', }] } }


'ecommerce': { 'purchase': { 'actionField': {'step': 4}, 'products': [{
'name': 'Spirit Pack', 'id': '12345', 'price': '55', }] } }

How can I return the array named products when the second level of layer object is different.

Simon Breton
  • 2,638
  • 7
  • 50
  • 105
  • 2
    Why do you need (I'm inferring) the same code to be able to get the products array from both objects? – Jake Worth Apr 12 '19 at 23:35
  • Thanks! The context is particular. It is related to Google Tag Manager. I'm just able to access this two variables in a different "state' but I need a function so I can return the product array each time. – Simon Breton Apr 12 '19 at 23:37
  • Will the `ecommerce` object always have just one property? Use `Object.keys(x.commerce)[0]` to get that property name. – Barmar Apr 12 '19 at 23:44

1 Answers1

0
const fxn = (ecommerce) => {
  let keys = Object.keys(ecommerce);
  return ecommerce[keys[0]]['products'];
}

The function is very fragile, as it only works if the object is the same shape as above with only a single key within the ecommerce object, but it would do the trick here.