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

2 Answers 2

3

Take the values of the object.

{
  Object.values(this.state.Products).map((product, i) => {
    return (
      <div>
        <Product product_data={product}/>
      </div>
    );
  })
}
Sign up to request clarification or add additional context in comments.

Comments

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>

2 Comments

It's the same solution Junius L and it does'nt work.. Thank you for your help and if you want to see, FurkanO has resolved my problem !
No problem, although updated. I would still note spreading the object would remove an unneeded prop.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.