如何在React.js中遍历数组对象

时间:2019-07-10 10:37:52

标签: reactjs dictionary

我现在正在从数据库中获取一些数据如何从此处显示结果项 数据如下 enter image description here

<div className="row">
                        { this.state.product.length > 0 ? this.state.product.map(product =>
                          <div className="col-lg-4 col-md-6 txt-center m-b-40" >
                                   <div className="plan-bx">
                                    <h1>{product.product}</h1>
                                    <p>Plan</p>
                                    <br/>
                                    <div>
                                    <h2>Free</h2>
                                    {this.state.product.map(p => p.result.map(r =>
                                    <span>

                                    <hr/>
                                    <br/>
                                    <h3>{r.fprice}</h3>
                                    <h4><span>5,999₹ </span>/ year</h4>

                                    </span>
                         ) )}
                                    <br/>

                                </div>
                            </div>

                            <a className="btn-view" href="">View Details</a>

                            </div>
                              ):null}

enter image description here

我是ReactJS的新手 谢谢

2 个答案:

答案 0 :(得分:1)

这是如何实现它的示例。

var data = {
  product: [
    {
      name: 'product1', 
      result: [{ price: 10, name: 'price'}, { price: 2, name: 'discount' }]
    },
    {
      name: 'product2', 
      result: [{ price: 200, name: 'price'}, { price: 50, name: 'discount'}]
    }
  ],
  
}

// Example class component
class App extends React.Component {
  render() {
    return (
      <div className='product-card'>
        {data.product && !!data.product.length && data.product.map(p => 
          <div>
            {p.name}
            
            {p.result.map(r => 
              <div>{r.name}<br />{r.price}$</div>
            )}
          </div>
        )}
      </div>
    );
  }
}

// Render it
ReactDOM.render(
  <App />,
  document.getElementById("react")
);
.product-card {
  display: flex;
}

.product-card-result {
  margin: 15px 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="react"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

答案 1 :(得分:0)

这将帮助您:

let prices = [];
if (data.product.length > 0) {
  prices = data.product.map(p => p.result.map(r => r.inrprice))
}
prices.map(price => <div>{price}</div>))

请粘贴示例JSON,以获得更准确的答案。