javascript - How can I map a nested array from JSON? - Stack Overflow

Bear with me, I am not good with words, Here, I'll try my best to explain on my issues with mappin

Bear with me, I am not good with words, Here, I'll try my best to explain on my issues with mapping the nested data in array, I am guessing this term would be called "fetching data from local API with ReactJS" This code below is the data inside the data.js as "local API"

    export default[
    {
        name: "John Doe",
        position: "developer",
        experiences: [
            {   
                id: 0,
                job:"developer 1",
                period: "2016-2017",
                description: "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laudantium nesciunt recusandae unde. Qui consequatur beatae, aspernatur placeat sapiente non est!" 
            },
            {
                id: 1,
                job:"developer 2",
                period: "2015-2016",
                description: "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laudantium nesciunt recusandae unde. Qui consequatur beatae, aspernatur placeat sapiente non est!" 
            },
            {
                id: 2,
                job:"developer 3",
                period: "2014-2015",
                description: "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laudantium nesciunt recusandae unde. Qui consequatur beatae, aspernatur placeat sapiente non est!" 
            }

        ]

    }
]

And the code below show two ponent files the index.js and App.js in ReactJS

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App'
import data from './data/dataJS';


ReactDOM.render(
     <App data={data} />, 
      document.getElementById('root'));

App.js

import React, { Component } from 'react';
import './App.css';

class App extends Component {
  render() {
     const {data} = this.props;
      const resume = data.map(info => {

        //console log
        console.log(info.name);
        console.log(info.position);
        console.log(info.experiences);
        console.log(info.experiences.job);

        //browser render
        return (
          <div>
              {info.name}
              <br/>
              {info.position}

           </div>
          )
        });
      });

    return (
      <div>
          {<p>{resume}</p>}
      </div>
    );
  }
}

So far, I am able to fetch the data as confirmed from browser console.log and render out two data info.name into John Doe and info.position into developer without problem.

Now, If I added this string <li key="experience.id">{info.experiences.job}</li> beneath {info.position} I will get an error.

Objects are not valid as a React child (found: object with keys {id, job, period, description}). If you meant to render a collection of children, use an array instead.

I assume, the way I set up array is incorrect. But the console.log of info.experiences shown result of (3) arrays of experiences. But The console log on info.experiences.job show undefined. Yet I am unable to figure out the what the problem are, what could be wrong?

I've spend two days trying to find solution and I am not any getting luck.

Any suggestions?

Bear with me, I am not good with words, Here, I'll try my best to explain on my issues with mapping the nested data in array, I am guessing this term would be called "fetching data from local API with ReactJS" This code below is the data inside the data.js as "local API"

    export default[
    {
        name: "John Doe",
        position: "developer",
        experiences: [
            {   
                id: 0,
                job:"developer 1",
                period: "2016-2017",
                description: "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laudantium nesciunt recusandae unde. Qui consequatur beatae, aspernatur placeat sapiente non est!" 
            },
            {
                id: 1,
                job:"developer 2",
                period: "2015-2016",
                description: "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laudantium nesciunt recusandae unde. Qui consequatur beatae, aspernatur placeat sapiente non est!" 
            },
            {
                id: 2,
                job:"developer 3",
                period: "2014-2015",
                description: "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laudantium nesciunt recusandae unde. Qui consequatur beatae, aspernatur placeat sapiente non est!" 
            }

        ]

    }
]

And the code below show two ponent files the index.js and App.js in ReactJS

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App'
import data from './data/dataJS';


ReactDOM.render(
     <App data={data} />, 
      document.getElementById('root'));

App.js

import React, { Component } from 'react';
import './App.css';

class App extends Component {
  render() {
     const {data} = this.props;
      const resume = data.map(info => {

        //console log
        console.log(info.name);
        console.log(info.position);
        console.log(info.experiences);
        console.log(info.experiences.job);

        //browser render
        return (
          <div>
              {info.name}
              <br/>
              {info.position}

           </div>
          )
        });
      });

    return (
      <div>
          {<p>{resume}</p>}
      </div>
    );
  }
}

So far, I am able to fetch the data as confirmed from browser console.log and render out two data info.name into John Doe and info.position into developer without problem.

Now, If I added this string <li key="experience.id">{info.experiences.job}</li> beneath {info.position} I will get an error.

Objects are not valid as a React child (found: object with keys {id, job, period, description}). If you meant to render a collection of children, use an array instead.

I assume, the way I set up array is incorrect. But the console.log of info.experiences shown result of (3) arrays of experiences. But The console log on info.experiences.job show undefined. Yet I am unable to figure out the what the problem are, what could be wrong?

I've spend two days trying to find solution and I am not any getting luck.

Any suggestions?

Share Improve this question edited Sep 27, 2017 at 18:54 isherwood 61.2k16 gold badges121 silver badges170 bronze badges asked Sep 27, 2017 at 18:39 sirrussirrus 3431 gold badge7 silver badges17 bronze badges 7
  • 1 info.experiences is an array. console.log(info.experiences) should show you that. So to access the job property, you'd have to do info.experiences[0].job or something similar. – Mike Cluck Commented Sep 27, 2017 at 18:41
  • info.experiences[i].job – hjm Commented Sep 27, 2017 at 18:42
  • why you got 2 return in your App render? – Sagiv b.g Commented Sep 27, 2017 at 18:43
  • @Sag1v One is inside of the data.map. It's turning resume into an array of elements. – Mike Cluck Commented Sep 27, 2017 at 18:44
  • you got syntax error there, after the first return you closed the render function – Sagiv b.g Commented Sep 27, 2017 at 18:46
 |  Show 2 more ments

1 Answer 1

Reset to default 3

You got couple of things to fix here:

  • You got a syntax error in your render function, in the first return you closed the the render function body, hence you can't reach the second return (it shouldn't even render and throw an error).
  • You are trying to reference an object in your key? you used a string. anyway keys should be unique to their siblings DOCS.

    <li key="experience.id">{info.experiences.job}</li>

  • This should be (but hold your horses we are not done yet!):

    <li key={experience.id}>{info.experiences.job}</li>

  • experience is undefined, i'm guessing you wanted to loop through experiences array:

    info.experiences.map(experience => <li key={experience.id}>{experience.job}</li>)

Anyway here is a running and working example:

const data = [
  {
    name: "John Doe",
    position: "developer",
    experiences: [
      {
        id: 0,
        job: "developer 1",
        period: "2016-2017",
        description: "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laudantium nesciunt recusandae unde. Qui consequatur beatae, aspernatur placeat sapiente non est!"
      },
      {
        id: 1,
        job: "developer 2",
        period: "2015-2016",
        description: "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laudantium nesciunt recusandae unde. Qui consequatur beatae, aspernatur placeat sapiente non est!"
      },
      {
        id: 2,
        job: "developer 3",
        period: "2014-2015",
        description: "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laudantium nesciunt recusandae unde. Qui consequatur beatae, aspernatur placeat sapiente non est!"
      }

    ]

  }
]


class App extends React.Component {
  render() {
    const { data } = this.props;
    const resume = data.map(info => {
      //browser render
      return (
        <div>
          {info.name}
          <ul>
          {
            info.experiences.map(experience => <li key={experience.id}>{experience.job}</li>)
          }
          </ul>
          {info.position}
        </div>
      );
    });

    return <div>{<p>{resume}</p>}</div>;
  }
}

ReactDOM.render(
  <App data={data} />,
  document.getElementById('root'));
<script src="https://cdnjs.cloudflare./ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare./ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

Edit
As a followup to your ments:

I almost never encounter any error except for when I try to assign it on nested array

Well as for your code in the render method of App.js:

render() {
    // console.log(this.props.name)
     const {data} = this.props;
     const resume = data.map((info) => {
        return (
          <div>
             {info.name}
             {info.experiences.map((experience, idx)=> 
                  <div >
                      <div key={experience.id} >{experience.job}</div>
             </div>)}
             {info.position}

          </div>
      )
    });

You got 2 issues:

  1. In first loop iteration you should pass a key to the root element as well, not only to the second loop.

    const resume = data.map((info, key) => {
                return (
                  <div key={key}>
                     {info.name}
                     // ...
    
  2. In the second loop, you passed the key to the child element and not the parent element of this loop:

    {info.experiences.map((experience, idx)=> 
                      <div >
                          <div key={experience.id} >{experience.job}</div>
                 </div>)}
    

    The key should be on the root element not the second element:

    {info.experiences.map((experience, idx) =>
                <div key={experience.id}>
                  <div>{experience.job}</div>
                </div>)}
    

Working example:

const data = [
  {
    id: "resume",
    name: "John Doe",
    position: "developer",
    experiences: [
      {
        id: 0,
        job: "developer 1",
        period: "2016-2017",
        description: "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laudantium nesciunt recusandae unde. Qui consequatur beatae, aspernatur placeat sapiente non est!"
      },
      {
        id: 1,
        job: "developer 2",
        period: "2015-2016",
        description: "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laudantium nesciunt recusandae unde. Qui consequatur beatae, aspernatur placeat sapiente non est!"
      },
      {
        id: 2,
        job: "developer 3",
        period: "2014-2015",
        description: "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laudantium nesciunt recusandae unde. Qui consequatur beatae, aspernatur placeat sapiente non est!"
      }

    ]

  }
]

class App extends React.Component {


  render() {
    // console.log(this.props.name)
    const { data } = this.props;
    const resume = data.map((info, i) => {
      return (
        <div key={i}>
          {info.name}
          {info.experiences.map((experience, idx) =>
            <div key={experience.id}>
              <div>{experience.job}</div>
            </div>)}
          {info.position}

        </div>
      )
    });

    return (
      <div>
        {resume}
      </div>

    );
  }
}
ReactDOM.render(<App data={data} />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare./ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare./ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

BONUS
As for this ment:

I would have used codepen, but realize but its not possible to create two files i.e. index.js and App.js

You can use code sandbox it's great for react.
Here is a working example with your code in separate files link.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745135376a4613174.html

相关推荐

  • javascript - How can I map a nested array from JSON? - Stack Overflow

    Bear with me, I am not good with words, Here, I'll try my best to explain on my issues with mappin

    1小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信