Anish
Anish

Reputation: 558

reactjs ,jsx iterate over nested object

i have an reactjs application which contains all child object, i want to iterate over them few things i have tried like

cart.line_items.map(items =><CartPreview key={items.id} data = {items} />)} 

and cart preview is like bellow

import React from 'react'

export default (props) => {
 const { data } = props
return (
  <a href={Routes.spree_cart_path()}>
    <span className="glyphicon glyphicon-shopping-cart" />
  &nbsp;
    {I18n.t('spree.cart')}: {I18n.toCurrency(data.total)}
  </a>
 )
}

its print total of line_items object which is fine..

Now i want to go further (i want to get variant and image object in line items) in line item object and i did like

{ !cart.isFetching &&   cart.line_items.map
    ( 
        function(variant, key)
        { 
       return(
              Object.keys(variant).map
              (
                function(images)
                {
                 return
                      (  
                        <CartPreview  variant={variant} image={images} />
                      );
              }
            )
          )
      }
    )  
  } 

which gives undefined variant and line_items

Can anyone please help me ...

for understanding i have attached screen shot too...

enter image description here

Upvotes: 2

Views: 299

Answers (1)

Bruce Mu
Bruce Mu

Reputation: 893

Hope I understand your question correctly. Your code doesn't make much sense to me. No sure if the approach below is what you want. I assume that for each image, you want to render one CartPreview.

{ 
 !cart.isFetching && cart.line_items.map( 
      line_item => 
 line_item.variant.images.map(image => <CartPreview variant={line_item.variant} image={image} />))  
} 

I feel that you are a bit confused about Object.keys and map. You can go check the documents, it will give you a clear idea of iterating an array in javascript.

Upvotes: 1

Related Questions