1

Access to data inside an object to send it to a React Component

I'm trying to recover data inside an object which looks like this :

{89: {…}, 91: {…}, 92: {…}}

89: {name: "Confiture de Myrtilles", product_id: "737", _wc_review_count: "0", _wc_rating_count: "a:0:{}", _wc_average_rating: "0", …}

91: {name: "Poires Guyot (bio)", product_id: "690", _wc_review_count: "0", _wc_rating_count: "a:0:{}", _wc_average_rating: "0", …}

92: {name: "Pommes Pinova (bio)", product_id: "700", _wc_review_count: "0", _wc_rating_count: "a:0:{}", _wc_average_rating: "0", …}


I want to work on each "index" ( 89,91,....) and send them one per one to my React component.

So for example the first thing which will use by my React Component will be

{name: "Confiture de Myrtilles", product_id: "737", _wc_review_count: "0", _wc_rating_count: "a:0:{}", _wc_average_rating: "0", …}

I've tried to use map function like this but it does'nt work :


{this.state.Products.map((product, i) => {
                        return (
                            <div>
                            <Product product_data={product}/>
                            </div>
                        );
})}

Thanks if you can help me and tell me if you need more informations

Community
  • 1
  • 1

2 Answers2

3

Take the values of the object.

{
  Object.values(this.state.Products).map((product, i) => {
    return (
      <div>
        <Product product_data={product}/>
      </div>
    );
  })
}
FurkanO
  • 7,100
  • 5
  • 25
  • 36
0

You have an object not an array.

Make an array from object:

const products = Object.values(this.state.products);

Loop over products:

products.map(item => <Product product_data={item}/>)

Let me know how you get on.

——

IMO: I would spread the data, then in the component access each name in <Product />.

Example:

products.map(item => <Product {...item} />)

Then in your component <Product />:

<h1>{this.props.name}</h1>
Neil
  • 971
  • 2
  • 12
  • 33