Matthew Farlymn Matthew Farlymn -4 years ago 114
Javascript Question

Show specific number of array objects (React)

I am trying to loop through JSON data and only show the first "4" results, but through all of my searching most of the answers I have seen use forEach() or map() which loops through all of the data. I have tried using for(), but it results in nothing displaying on the page. If anyone can help or direct me to an answer I haven't been able to find that would be great!

{this.state.products.map(function(product) {
return(
<div className="col-xs-12 col-sm-6 col-md-3" key={product.productId}>
<img src={product.productImage1} Image1 alt="Logo"/>
<h3>{product.productTitle}</h3>
<p>{product.productDesc}<a href="/">Learn More</a></p>
</div>
);
})}

Answer Source

You can use slice method before map.

{this.state.products.slice(0, 4).map(function(product) {
    return(
        <div className="col-xs-12 col-sm-6 col-md-3" key={product.productId}>
            <img src={product.productImage1} Image1 alt="Logo"/>
            <h3>{product.productTitle}</h3>
            <p>{product.productDesc}<a href="/">Learn More</a></p>
        </div>
    );
})}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download