简体   繁体   English

如何将此数据映射到React中的json数组?

[英]How to map this data to a json array within React?

I have a Rest API which returns data in json of the form : 我有一个Rest API,它以json形式返回数据:

["1.6.3","1.6.4","1.6.5","1.6.6","1.7.0","1.7.2"]

I need the data in this format: 我需要以下格式的数据:

var options = [{ value: 'one', label: 'One' }, { value: 'two', label: 'Two', clearableValue: false }
 ];

After fetching the data I am using the following code to map the data in the required format: 提取数据后,我正在使用以下代码以所需的格式映射数据:

if (this.state.coreversions) {
                var options = [
                    this.state.coreversions.map(versions =>
                        `{ value: '${versions}', label: '${versions}' },`
                    )
                ];
            }

Here the variable version is equal to a single value of the data returned by the Rest API 这里的变量版本等于Rest API返回的数据的单个值

Any help would be appreciated. 任何帮助,将不胜感激。

Array#map returns an array, therefore you do not have to enclose it within square brackets. Array#map返回一个数组,因此您不必将其括在方括号内。

Amend your code as follows: 修改您的代码,如下所示:

if (this.state.coreversions) {
  var options = this.state.coreversions.map(
    versions => ({value: versions, label: versions})
  );
}

 // simplified this.state.coreversions to just coreversions // only for the purposes of this snippet var coreversions = ["1.6.3","1.6.4","1.6.5","1.6.6","1.7.0","1.7.2"]; if (coreversions) { var options = coreversions.map( versions => ({value: versions, label: versions}) ); } console.log(options); // logs out an array of objects: // [ // { value: '1.6.3', label: '1.6.3' }, // { value: '1.6.4', label: '1.6.4' }, // { value: '1.6.5', label: '1.6.5' }, // { value: '1.6.6', label: '1.6.6' }, // { value: '1.7.0', label: '1.7.0' }, // { value: '1.7.2', label: '1.7.2' } // ] 

I think your map function is returning an array of strings instead of objects. 我认为您的map函数返回的是字符串数组,而不是对象。 Should be like: 应该是这样的:

return { value: '${versions}', label: '${versions}' } 返回{值:'$ {versions}',标签:'$ {versions}'}

Note how the above does not have the ticks surrounding the entire line. 请注意,上面没有整行周围的刻度线。

React-Select expects an array of objects, not an array of strings. React-Select需要一个对象数组,而不是字符串数组。

You can loop through the data, put these values in a object and push it in an array like the following: 您可以遍历数据,将这些值放在对象中,然后将其放入数组,如下所示:

 var results = ["1.6.3", "1.6.4", "1.6.5", "1.6.6", "1.7.0", "1.7.2"]; var selectData= []; for (result of results) { selectData.push({ value: result, label: result }); } console.log(selectData); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM