2

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

Anish
  • 558
  • 3
  • 10
  • 33

1 Answers1

1

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.

Bruce Mu
  • 893
  • 11
  • 22
  • That's working fine. Can you please suggest me some blogs/tutorial to understand Object.keys and map in JS/Reactjs – Anish May 08 '17 at 06:31
  • 1
    @Anish Happy to hear that. Object.keys and map are all vanilla javascript. Not related to react.js. I feel that the documentation on Mozilla is good enough already. Object.keys: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/keys map: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map?v=example – Bruce Mu May 08 '17 at 12:59