3

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.

test
  • 2,429
  • 15
  • 44
  • 81
  • Can you show us what you've tried? – Andrew Li Aug 07 '17 at 04:53
  • Possible duplicate of [How to get all properties values of a Javascript Object (without knowing the keys)?](https://stackoverflow.com/questions/7306669/how-to-get-all-properties-values-of-a-javascript-object-without-knowing-the-key) – Henrik Andersson Aug 07 '17 at 05:07
  • Possible duplicate of [How to convert key-value pair object into an array of values in ES6?](https://stackoverflow.com/questions/45411208/how-to-convert-key-value-pair-object-into-an-array-of-values-in-es6) – Shubham Khatri Aug 07 '17 at 05:12
  • Isn't a lodash _.toArray going to work here? – Tianhao Zhou Aug 07 '17 at 05:12

1 Answers1

5

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);
Henrik Andersson
  • 45,354
  • 16
  • 98
  • 92