【问题标题】:Javascript ES6: Get specific array from inside of JSON array and iterate them using mapJavascript ES6:从 JSON 数组内部获取特定数组并使用映射对其进行迭代
【发布时间】:2018-12-11 10:35:53
【问题描述】:

我在https://api.myjson.com/bins/9jyq4 有一个 JSON

"response": [{
    "id": "1",
    "title": "Star Wars",
    "project": [
      "Star Wars Proj1",
      "Star Wars Proj2",
      "Star Wars Proj3",
      "Star Wars Proj4"
    ]
  },
  {
    "id": "2",
    "title": "Back to the Future",
    "project": [
      "Back to the Future Proj1",
      "Back to the Future Proj2",
      "Back to the Future Proj3",
      "Back to the Future Proj4"
    ]
  },
  ..
  ..

我有两个选择器。 “标题”和“项目” 我正在使用填充标题选择器。

<Picker
  mode="dialog"
  selectedValue={this.state.Movietitle}
  onValueChange={(itemValue, itemIndex) => 
  this.setState({ Movietitle: itemValue });
  }
  enabled={!this.state.inRide}
  >
  { 
    this.state.responseData.map((item) => (
    <Picker.Item label={item.title} value={item.id} key={item.id} />))
  }
</Picker>

所以现在我想使用从第一个选择器中选择的选项填充第二个选择器“项目”。只需要帮助进行地图查询。谢谢

【问题讨论】:

  • 特定 id 的数组,它们是什么?
  • 你到底想要什么。给个样本吧。
  • 更新了问题。请看

标签: javascript json reactjs react-native ecmascript-6


【解决方案1】:

使用 filter 方法获取 id 匹配的对象的 tan 数组,然后对其使用 map 方法

let response = [{
    "id": "1",
    "title": "Star Wars",
    "project": [
      "Star Wars Proj1",
      "Star Wars Proj2",
      "Star Wars Proj3",
      "Star Wars Proj4"
    ]
  },
  {
    "id": "2",
    "title": "Back to the Future",
    "project": [
      "Back to the Future Proj1",
      "Back to the Future Proj2",
      "Back to the Future Proj3",
      "Back to the Future Proj4"
    ]
  }
]

function getObject(srchId) {
  let __obj = response.filter(function(item) {
    return item.id === srchId;


  })
  return __obj;
}

getObject('2').map(function(item) {

  //rest of the code
})

【讨论】:

    【解决方案2】:

    您应该能够通过finding 当前选择的响应项访问每个​​项目标题,并简单地映射到该响应项的project 属性中的每个项目。

    像这样:

    render() {
        const { responseData, Movietitle, selectedProject } = this.state;
        const selectedMovie = responseData.find(item => item.id === Movietitle);
    
        return (
            <Picker
                mode="dialog"
                selectedValue={selectedProject}
                onValueChange={project => this.setState({ selectedProject: project })}
            >
                { 
                    selectedMovie.project.map((project, projectIndex) => (
                        <Picker.Item label={project} value={project} key={`${Movietitle}-${projectIndex}`} />
                    ))
                }
            </Picker>
        );
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-26
      • 1970-01-01
      • 2022-01-20
      • 1970-01-01
      • 1970-01-01
      • 2017-12-17
      • 2019-06-26
      • 1970-01-01
      相关资源
      最近更新 更多