首页 > 解决方案 > 通过 react-native 中的键值迭代 JSON 数组

问题描述

无论如何要从 json 数组中获取对象中的值。我需要从基于另一个值的对象中获取一个值。

我的代码如下:

export default class StandardComp extends Component {
    constructor(props) {
        super(props)
        this.state = {
           id: '',
           email: 'abc@gmail.com',
           dataSource: []
        };    
    }

    componentDidMount(){
        fetch(someURL, {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json'
           }
        })
        .then((response) => response.json())
        .then((responseJson) => {
            this.setState({dataSource: responseJson})
            //dunno what to do here
        })
        .catch((error) => {
           console.error(error);
        })
    }
}

我的“responseJson”是这样的。然后提供键值(abc@gmail.com),我怎样才能得到字符串“abcdef”?

[
   {
      "id": "qwerty",
      "email": "cat@gmail.com",
      "name": "cat"
   },
   {
      "id": "abcdef",
      "email": "abc@gmail.com",
      "name": "abc"
   }         
   {
      "id": "owowao",
      "email": "dog@gmail.com",
      "name": "dog"
   },
]

先感谢您。

标签: jsonreact-native

解决方案


找到匹配 email 的元素并返回 id。

数组::查找

const data = [
   {
      "id": "qwerty",
      "email": "cat@gmail.com",
      "name": "cat"
   },
   {
      "id": "abcdef",
      "email": "abc@gmail.com",
      "name": "abc"
   },       
   {
      "id": "owowao",
      "email": "dog@gmail.com",
      "name": "dog"
   },
];

const findIdByEmail = (data, email) => {
  const el = data.find(el => el.email === email); // Possibly returns `undefined`
  return el && el.id; // so check result is truthy and extract `id`
}

console.log(findIdByEmail(data, 'cat@gmail.com'));
console.log(findIdByEmail(data, 'abc@gmail.com'));
console.log(findIdByEmail(data, 'gibberish'));


推荐阅读