通过react-native中的键值迭代JSON数组

时间:2019-01-09 05:56:04

标签: json react-native

是否有从json数组中获取对象中的值的方法。我需要从基于另一个值的对象中获取一个值。

我的代码如下:

class Object:
    def __init__(self, mesh):
        self.mesh = mesh

    def __getattr__(self, name):
        return getattr(self.mesh, name)

    def __setattr__(self, name, value):
        if name in self.__dict__ or name == 'mesh':   # special case for 'mesh' here!
            super().__setattr__(name, value)
        else:
            setattr(self.mesh, name, value)

我的“ responseJson”就是这样。然后提供键值(abc@gmail.com),如何获取字符串“ abcdef”?

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);
        })
    }
}

谢谢。

2 个答案:

答案 0 :(得分:2)

找到与电子邮件匹配的元素并返回ID。

array::find

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'));

答案 1 :(得分:1)

代码将取决于您如何获得值abc@gmail.com

您可能需要通过道具将其作为参数传递给componentDidMount?或将其提取为单独的函数。这只是取决于。

这样的事情是我要说的最基本的方法。

const value = responseJson.filter(obj => obj.email === 'abc@gmail.com')[0].id

这是在您的课堂中实现的。

export default class StandardComp extends Component {
  ...

  componentDidMount(){
    fetch(someURL, {
    method: 'GET',
    headers: {
        'Content-Type': 'application/json'
       }
    })
    .then((response) => response.json())
    .then((responseJson) => {
        this.setState({ dataSource: responseJson })
        const { email } = this.state
        const value = responseJson.filter(obj => obj.email === email)[0].id

    })
    .catch((error) => {
       console.error(error);
    })
  }

}

相关问题