0

I have a Rest API which returns data in json of the form :

["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

Any help would be appreciated.

3 Answers 3

2

Array#map returns an array, therefore you do not have to enclose it within square brackets.

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' }
//  ] 

Sign up to request clarification or add additional context in comments.

1 Comment

Amended the syntax to remove the unnecessary return statement
0

I think your map function is returning an array of strings instead of objects. Should be like:

return { value: '${versions}', label: '${versions}' }

Note how the above does not have the ticks surrounding the entire line.

Comments

0

React-Select expects an array of objects, not an array of strings.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.