I'm developing a React application where I need to convert a key-value object like this:
{
0: 'John',
1: 'Tim',
2: 'Matt'
};
To an array of just the values like this:
['John', 'Tim', 'Matt']
How do I accomplish this?
const obj = {
0: 'John',
1: 'Tim',
2: 'Matt'
};
const arr = /* ??? */;
You can make use of Object.values
command.
According to the docs.
Object.values()
returns an array whose elements are the enumerable property values found on the object. The ordering of the properties is the same as that given by looping over the property values of the object manually
Although it is an ES2017
solution but since you are using react, you can include stage-0
as a preset for babel
and access this functionality
var data ={
0: 'John',
1: 'Tim',
2: 'Matt'
};
var newdata = Object.values(data);
console.log(newdata);
there are other methods like Object.keys
which gives you all the keys as an array and Object.entries
method returns an array of a given object's own enumerable property [key, value]
pairs which might also be useful to you