json - 通过 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"
},
]
先感谢您。
解决方案
找到匹配 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'));
推荐阅读
- go - Go 项目不从 github 拉取导入更新
- python - Tried installing FastAi but I got "ERROR: No matching distribution found for torchvision>=0.7"
- c - Using main(int arc, char *argv[])?
- hyperlink - How to include the last word of hyperlink text in TRichEdit in the blue, underline format of the rest?
- c - Function return via pointer doesn't work correctly
- javascript - NodeJS createWriteStream JavaScript heap out of memory
- reactjs - React Incorrect render when combine withRouter/withStyles and mobx's observer
- lambda - 继续通过式程序
- reactjs - react-toastify showing twice with SSR
- javascript - Asp.net 部分视图 - 单击后设置 html 和 css - 不改变它的状态