如何在JavaScript中将JSON对象转换为String数组和数字

时间:2017-06-13 10:09:24

标签: javascript arrays json

我从GET请求到API端点有以下响应:

{ 
  "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,
                })
            }
        })

我想要做的是从类别中获取数据并将其打印为String和number(id和num_of_subs作为数字,标签和url作为String)。这是我做的:

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,label和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(),但似乎都没有工作,因为它们都会导致&#34; object&#34;当我打印出值的类型。

请问有没有办法解决这个问题?

1 个答案:

答案 0 :(得分:2)

您的代码无效,因为您没有遍历对象数组。您只是返回数组的对象。这就是你无法提取值

的原因

var items = [{
  "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
      },
    ],
  }

}]

setState = [];
var catagories = items.map(x => x.data.categories);
catagories = catagories.reduceRight(x => x.cantact([]));
getCategory = (values) => {
  for (let value of values) {
    setState.push({
      category_id: value.id,
      selected_category: value.label,
      numSubs: value.num_of_subs
    })
  }
}

var output = getCategory(catagories)
var results = setState.filter(x => x.numSubs > 0)

console.log(results);