通过反应获取json对象数据

Ash*_*Ash 3 json jsx reactjs

我试图从这样的json中提取数据,这被导入为"值"

{
  "content": {
      "person": [
        {
          "name": "Test"
          "age" : "24:
        }
    ]
 }
}
Run Code Online (Sandbox Code Playgroud)

我正在使用.map如下,但得到错误,.default.map is not a function我相信这是因为我有对象而不是数组,我尝试了一堆东西,object.keys但我在整个地方都得到错误,任何方向将不胜感激.

import values from './sample.json'

const vals = values.map((myval, index) => {
    const items = person.items.map((item, i) => {

        return (
            <div>{item.name}</div>
        )
    })

    return (
        <div>{items}</div>
    )
})
Run Code Online (Sandbox Code Playgroud)

Kum*_*arM 8

我认为您的数据和代码存在一些错误.但是在修复了这些并将名称从"人"更改为"人员"之后,如果这就是您所追求的,那么这里的代码就是您要执行的操作:

var data = {
  content: {
      people: [
        {
          name: "Test",
          age : 24
        },
        {
          name: "Foo",
          age: 25
        }
      ]
   }
};

var App = React.createClass({
  render: function() {
    var people = data.content.people.map(function(person){
      return (<div>{person.name}</div>);
    });

    return (<div>{people}</div>)
  }
}); 

ReactDOM.render(<App/>, document.getElementById("app"));
Run Code Online (Sandbox Code Playgroud)

这里是JSBin:https://jsbin.com/coyalec/2/edit?html,js,output

更新:我正在用更详细的例子更新答案.它现在更一般地处理数据,就像它不假设"内容"的条目一样,但是它知道像'people'或'pets'这样的每个类型都是一个数组.

var data = {
  content: {
      people: [
        {
          name: "Test",
          age : 24
        },
        {
          name: "Foo",
          age: 25
        }
      ],
      pets: [
        {
          name: "Sweety",
          age: 3
        },
        {
          name: "Kitty",
          age: 5
        }
      ]
   }
};

var App = React.createClass({
  render: function() {
    //Get the keys in data.content. This will return ['people', 'pets']
    var contentKeys = Object.keys(data.content);

    //Now start iterating through these keys and use those keys to
    //retrieve the underlying arrays and then extract the name field
    var allNames = contentKeys.map((t) => 
                       data.content[t].map((e) => (<div>{e.name}</div>))
                       );

    return (<div>{allNames}</div>)
  }
}); 

ReactDOM.render(<App/>, document.getElementById("app"));
Run Code Online (Sandbox Code Playgroud)

这是最新的JSBin:https://jsbin.com/coyalec/4/edit html,js,output