Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React convert props Objects into array then setState

I need to convert this props:

enter image description here

into this array:

this.setState({
            locations: [
                { label: 'California', value: 'california' },
                { label: 'Nevada', value: 'nevada' },
            ]
});

originally i was using this plugin and wanted to replace its default values with my props but cant convert it.

like image 928
test Avatar asked Feb 05 '26 12:02

test


1 Answers

Depending on your flavor of JavaScript and preference of writing

Taking advantage of the for .. in operator, which comes with draw backs. It'll loop over all enumerable properties even the ones from the prototype.

var arr = [];
for (var key in myObject) {
  arr.push(myObject[key]);
}

or by using the Object.keys method

var arr2 = Object.keys(myObject).map(function (i) {
  return myObject[i];
});

or lastly, if you're running an Babel transpiled app, Object.values

var arr3 = Object.values(myObject);
like image 67
Henrik Andersson Avatar answered Feb 08 '26 00:02

Henrik Andersson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!