我已经从一个GET请求到一个API结束点以下响应:如何JSON对象转换为字符串的数组和数量在JavaScript
{
"success": true,
"data": {
"categories": [
{
"id": 1,
"label": "Default",
"url": "default",
"num_of_subs": 0
},
{
"id": 2,
"label": "Pet Grooming",
"url": "pet-grooming",
"num_of_subs": 2
},
],
}
}
这里是取代码:
const sendRegisterData = fetch('https://sg.cuzzey.com/api/listings/categories', {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
})
.then((response) => response.text())
.then((responseText) => {
var response_final = JSON.parse(responseText);
if (response_final.success) {
this.setState({
categories: response_final.data.categories,
})
}
})
我想要做的是从类别中获取数据并将其作为字符串和数字(id和num_of_subs作为数字,标签和url作为字符串)打印出来。下面是我做的:
const category_options = this.state.categories.map(category => {
return [<Text key={category.id} style={styles.smallTextBox}> {category.id} {'\n'}</Text>,
<Text key={category.label} style={styles.smallTextBox}> {category.label} {'\n'}</Text>,
<Text key={category.num_of_subs} style={styles.smallTextBox}> {category.num_of_subs} {'\n'}</Text>]
})
<ModalDropdown options={category_options} onSelect={(idx, label) => this.getCategory(idx, label)}>
<Text style={styles.smallTextBox}> {this.state.selected_category} </Text>
</ModalDropdown>
我用这个代码以获取ID,标签和num_of_subs的价值:
getCategory = (idx, value) => {
this.setState({ category_id: value[0], selected_category: value[1], numSubs: value[2] })
}
当我打印出来CATEGORY_ID,selected_category和numSubs,该值是正确的。但是,它们是对象类型而不是字符串/数字。我想操纵这些值,但我不知道如何将它们转换为字符串/数字。我已经尝试过使用String(),Number(),parseInt(),JSON.parse(),toString(),但似乎没有任何工作,因为它们都会导致“对象”,当我打印出的typeof值。
我可以问有没有办法解决这个问题?
可以提供输出的一个例子,你想 – Rick
我希望能够做一些事情,如: '如果(这一点。 state.numSubs> 0){ render_something() 否则{ render_something_else() }' 目前numSubs是不是一个数字,所以我不能用它来与什么比较。 –