regetskcob
regetskcob

Reputation: 1191

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.

// @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. But why?

My JSON looks like

{
    "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?

Using peoples.peoples.map results in the following react-error:

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.

Upvotes: 0

Views: 91

Answers (3)

Hemerson Carlin
Hemerson Carlin

Reputation: 7424

Your peoples object has another peoples property in it.

So instead of peoples.map(...), use peoples.peoples.map(...)

Also, your are rendering each name wrongly inside the map loop:

{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.

Upvotes: 5

jake
jake

Reputation: 488

You can cleanly extract (destructure) the part you really need like this:

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

Upvotes: 0

Joel
Joel

Reputation: 86

I think you intent to do peoples.peoples.map(name => {});

When you require the json file you are importing it as a root object. The peoples array will then be (imported as).peoples. i.e peoples.peoples.map();

Upvotes: 0

Related Questions