Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
609 views
in Technique[技术] by (71.8m points)

javascript - Render a nested array of objects in react

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}]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

you can make use of nested map to map over the inner child obejcts 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>
              );
        }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...