1

I map through multiple objects. [{name:"y", country:"US", cities:[obj,obj,ob]},{name:"y", country:"US", cities:[obj,obj,ob]}]

How can I nest a loop so I first iterate through the objects and then iterate through (in this example) cities?Thanks!!

my render function without the nested look looks like this :

render() {
  const persons = this.state.name.map((item, i) => {
    return (
      <div>
        <h5> {item.name} </h5> 
        <h5> {item.country} </h5> 
        //here I would like to show the cities
      </div>
    );
  });
  return (
    <div>
      <div className = "panel-list"> 
        All: {persons} 
      </div> 
    </div>
  );
}

Cities object example:

[{visitors:34, rating:4}, 
 {visitors:1234, rating:1},
 {visitors:124, rating:2}]

1 Answer 1

3

you can make use of nested map to map over the inner child objects as well like

     render() {
            const persons = this.state.name.map((item, i) => {
                return (
                   <div>
                      <h5> {item.name} </h5> 
                      <h5> {item.country} </h5> 
                      <h4>{item.cities.map((city) => {
                             return (<li>{/* city object details here*/}</li>)
                       })}</h4>
                   </div>);
            });
            return (
            <div>
                <div className = "panel-list"> 
                    All: {persons} 
                </div> 
            </div>
              );
        }
Sign up to request clarification or add additional context in comments.

8 Comments

Thanks for your answer. If I use your solution, i get wrong results. Lets say I (as an example) 5 countries. Each country has 5 cities. Then I would get France plus all cities for all 5 countries instead of just one
As I under from your data object {name:"y", country:"US", cities:[obj,obj,ob]} cities is cities within country US, Is it? How does your cities object look like. I suppose you need to add that in your question as well
I edited my question with the countries object. so if I would do <h4>{city.visitor}</h4> I would not get that per country, but it would look like France, (visitor) 34,1234,124
In your question, the object contains name country and cities but not countries See {name:"y", country:"US", cities:[obj,obj,ob]}
sorry it was a type-meant cities not countries
|

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.