0

I have the following nested object with objects and arrays :

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

I'd like to extract the product array however I don't know the second property name, it's a dynamic value changing all the time.

Normally I should be able to do something like this var x = ecommerce.[dynamicvalue].products

However since I never know this second value how can I do?

Simon Breton
  • 2,638
  • 7
  • 50
  • 105

1 Answers1

1

Access the Object.values of ecommerce to get an array of every subobject (thereby skipping the "dynamicvalue"), and then you can do what you need to with that subobject's products:

const obj = {
  'ecommerce': {
    '[dynamicvalue]': {
      'actionField': {
        'step': 4
      },
      'products': [{
        'name': 'Spirit Pack',
        'id': '12345',
        'price': '55',
      }]
    }
  }
};

const [{ products }] = Object.values(obj.ecommerce);
console.log(products);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320