【问题标题】:How do I access all values from nested JSON Array?如何访问嵌套 JSON 数组中的所有值?
【发布时间】:2019-01-22 13:26:21
【问题描述】:

这是我的 JSON 数组:

    [{"id":"11",
"first_name":"John",
"last_name":"Doe",
"username":"Username1234",
"email":"example1426@gmail.com",
"who":"Person",
"user_images":[{"id":"114",
"username":"Hannah_L123",
"images":"resized_1522-20131219-creativity.jpg","date":"12\/04\/2017"}]}]

我不使用第一个数组,但我确实使用第二个数组,如下所示:

  user_image:  responseJson[0].user_images.map(item => ({ ...item, progress: new Animated.Value(0), unprogress: new Animated.Value(1) }))

我只想从user_images 访问所有已映射的username。尝试这些不起作用:{this.state.user_image.username}//未定义 {this.state.user_image["username"]}//未定义

我做错了什么?

编辑:我知道怎么做:this.state.user_image[0].username,但是我如何console.log() 包含username 的所有数据?我只从控制台记录 3。

反应原生代码:

fetch('https://www.example.com/React/user.php')
      .then((response) => response.json())
      .then((responseJson) => {
        this.setState({
          user_image:  responseJson[0].user_images.map(item => ({ ...item, progress: new Animated.Value(0), unprogress: new Animated.Value(1) })),
          }, function() {
            const userImagesWithUsername = this.state.user_image.map(item => item.username != undefined);
            console.log(userImagesWithUsername);
        });
      })
      .catch((error) => {
        //console.error(error);
      });

【问题讨论】:

  • 您在尝试访问对象之前是否使用了 JSON.parse("your json")?
  • 不,我没有,我该怎么做?因为我从来没有需要使用JSON.parase@slashsharp

标签: arrays json object react-native jsx


【解决方案1】:

要获取包含username 的所有数据,您可以过滤user_image 数组。

const userImagesWithUsername = this.state.user_image.filter(item => item.username != undefined);

【讨论】:

  • 谢谢,但是当我在控制台记录这一切时,它会再次打印整个列表。
  • 如果整个列表包含一个用户名字段我认为是正常的!你真正想做什么?
  • 我只想要该列表中的所有usernames。如果可能的话,就在没有其他所有属性的情况下。
  • 啊,好吧!然后只需添加.map(item => item.username),它就会返回一个用户名数组
  • fetch('example.com/React/user.php') .then((response) => response.json()) .then((responseJson) => { this.setState({ user_image: responseJson[0]. user_images.map(item => ({ ...item, progress: new Animated.Value(0), unprogress: new Animated.Value(1) })), }, function() { const userImagesWithUsername = this.state. user_image.map(item => item.username != undefined); console.log(userImagesWithUsername); }); }) .catch((error) => { });
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-06
  • 1970-01-01
  • 1970-01-01
  • 2019-12-05
  • 2018-08-16
  • 1970-01-01
相关资源
最近更新 更多