简体   繁体   English

Javascript-从JSON到对象的数组

[英]Javascript - Array from JSON to object

I have the following react class PeopleSelector within I want to get an array of peoples from my people.json. 我想在其中添加以下PeopleSelectorPeopleSelector ,以便从我的people.json获取一个人族。

// @flow

import React from 'react'

type Props = {
  currentPeople: string,
  setPeopleFn: (string) => void
}

class PeopleSelector extends React.Component {
  render() {
    let peoples = require('../data/people.json');

    return <select value={this.props.currentPeople} onChange={e => this.props.setPeopleFn(e.target.value)}>
      <style jsx>{`
        select {
          font-size: 20px;
          line-height: 20px;
          margin-bottom: 20px;
          min-width: 300px;
        }
      `}</style>
      {peoples.map(name => (
        <option key={name}>
          {name}
        </option>
      ))}
    </select>
  }
}

export default PeopleSelector

Sadly there occurs an error saying people.map is not a function. 不幸的是,发生错误,指出people.map不是一个函数。 But why? 但为什么?

My JSON looks like 我的JSON看起来像

{
    "peoples": [
        {
            "focusedTrackId": "MOBILE",
            "milestoneByTrack": {
                "COMMUNICATION": 3,
                "CRAFT": 2,
                "DESKTOP": 0,
                "MENTORSHIP": 2,
                "MOBILE": 3,
                "PROJECT_MANAGEMENT": 3,
                "SERVER": 0
            },
            "name": "Bocksteger, Daniel",
            "title": "Entwickler I"
        }
    ]
}

Is it not possible to render the JSON into an object of peoples? 不可能将JSON渲染为人的对象吗?

Using peoples.peoples.map results in the following react-error: 使用peoples.peoples.map导致以下反应错误:

Objects are not valid as a React child (found: object with keys 
{focusedTrackId, milestoneByTrack, name, title}). If you meant to 
render a collection of children, use an array instead.

Your peoples object has another peoples property in it. 您的peoples对象具有另一个peoples属性。

So instead of peoples.map(...) , use peoples.peoples.map(...) 因此,而不是peoples.map(...)使用peoples.peoples.map(...)

Also, your are rendering each name wrongly inside the map loop: 另外,您在map循环内错误地渲染了每个name

{peoples.peoples.map(people => (
  <option key={people.name}>
    {people.name}
  </option>
))}

option key={people.name}

I'd use some sort of id or unique identifier instead. 我会改用某种id或唯一标识符。

I think you intent to do peoples.peoples.map(name => {}); 我认为您打算这样做peoples.peoples.map(name => {});

When you require the json file you are importing it as a root object. 当您需要json文件时,您会将其作为根对象导入。 The peoples array will then be (imported as).peoples. 人员数组将被(导入为).peoples。 ie peoples.peoples.map(); 即peoples.peoples.map();

您可以像这样干净地提取(解构)您真正需要的零件:

let { peoples } = require('../data/people.json');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM