首页 > 解决方案 > 如何访问嵌套 JSON 数组中的所有值?

问题描述

这是我的 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) }))

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

我究竟做错了什么?

编辑:我发现了如何做到这一点:this.state.user_image[0].username但是我如何console.log()处理所有包含 a 的数据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);
      });

标签: arraysjsonobjectreact-nativejsx

解决方案


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

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

推荐阅读