如何在JSON对象(一个对象数组)中映射字段的数据

时间:2020-02-05 13:57:43

标签: reactjs react-redux

在我的react应用程序中,我正在使用一个API,该API在JSON响应中包含一个名为experience的字段,其中包含一个[{},{}]。在我看来,我需要显示该焦油里面的东西,并且我正在尝试使用.map()。 例如,我想显示一个体验列表。

获得体验的API响应是:

{
  "profileExperiences": [
    {
      "username": "Jakos",
      "experience": [
        {
          "image": "https://via.placeholder.com/150",
          "_id": "5e3975f95fbeec9095ff3d2f",
          "role": "Developer",
          "company": "Google",
          "startDate": "2018-11-09T23:00:00.000Z",
          "endDate": "2019-01-05T23:00:00.000Z",
          "area": "Copenhagen",
          "createdAt": "2020-02-04T13:47:37.167Z",
          "updatedAt": "2020-02-04T13:47:37.167Z"
        },
        {
          "image": "https://via.placeholder.com/150",
          "_id": "5e3978bf5e399698e20c56d4",
          "role": "Developer",
          "company": "IBM",
          "startDate": "2018-11-09T23:00:00.000Z",
          "endDate": "2019-01-05T23:00:00.000Z",
          "area": "Copenhagen",
          "createdAt": "2020-02-04T13:59:27.412Z",
          "updatedAt": "2020-02-04T13:59:27.412Z"
        }
      ],
      "experiences_count": 2
    }
  ]
}

我对expereince[]中的内容感兴趣,并且希望将这些数据显示在列表中。

我尝试过的是这个

const Experiences = () => {
  const dispatch = useDispatch();
  const { experiences } = useSelector(state => ({
    experiences: state.ExperiencesReducer.experiences
  }));

  console.log("My Exp", experiences.profileExperiences);

  useEffect(() => {
    dispatch(ExperiencesMiddleware.getAllExperiencesProfile(USERNAME));
  }, [dispatch]);

  return (
    <>
      <Container>
        <h1>Experience</h1>

        {experiences.profileExperiences &&
          experiences.profileExperiences.map((E, k) => (
            <Row key={k}>
              <ul>
                <li>{E.experience.role}</li>
              </ul>
            </Row>
          ))}
      </Container>
    </>
  );
};

export default Experiences;

我可以进行调试,直到{E.expereince.role}role未定义,但是经验却包含了我数组的2个obj,而且我不知道如何显示该列表。 我需要额外的映射还是需要更改方法?

2 个答案:

答案 0 :(得分:2)

//Your need one more mapping for experience array  
  {experiences.profileExperiences &&
              experiences.profileExperiences.map((P) =>P.experience).flat().map((E,k)=>(
                <Row key={k}>
                  <ul>
                    <li>{E.role}</li>
                  </ul>
                </Row>)
              )}

答案 1 :(得分:0)

E.experience.role不起作用,因为experience是一个数组。您将需要通过那些E.experience.map(value => value.role)进行映射或引用正确的索引E.experience[0].role

对于您的用例,也许可以使用以下方法:

experiences.profileExperiences[0].experience.map((E, k) => (
  <Row key={k}>
    <ul>
      <li>{E.role}</li>
    </ul>
  </Row>
))}

或者如果您要考虑多个profileExperiences

experiences.profileExperiences.map((E, k) => (
  <>
    <h1>Profile: {E.username}</h1>
    {E.exeriences.map(ex => (
      <Row key={k}>
        <ul>
          <li>{ex.role}</li>
        </ul>
      </Row>
    ))}
  </>
))}