How to convert enum into a key,value array in typescript?
10,761
Solution 1
Another alternative is to use a for ... in loop to iterate over the enums
keys and construct your desired array of objects.
var enums = {
'1': 'HELLO',
'2' : 'BYE',
'3' : 'TATA'
};
let res = [];
for (key in enums)
{
res.push({number: key, word: enums[key]});
}
console.log(res);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
Solution 2
You could map the entries with short hand properties.
var enums = { 1: 'HELLO', 2: 'BYE', 3: 'TATA' },
objects = Object.entries(enums).map(([number, word]) => ({ number, word }));
console.log(objects);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Solution 3
You can use Object.entries and map it to desired format
var enums = {
'1': 'HELLO',
'2' : 'BYE',
'3' : 'TATA'
};
let op = Object.entries(enums).map(([key, value]) => ({ number:key, word:value }))
console.log(op)
Solution 4
you can use Object.entries() with foreach and push it to an array like this
var enums = {
'1': 'HELLO',
'2' : 'BYE',
'3' : 'TATA'
};
var enumArray = []
Object.entries(enums).forEach(([key, value]) => enumArray.push({number : key, word : value}));
console.log(enumArray);
Solution 5
You can use Object.keys and map
var obj = {
'1': 'HELLO',
'2' : 'BYE',
'3' : 'TATA'
};
const result = Object.keys(obj).map(el => {
return {
number: el,
word: obj[el]
}
})
console.log(result)
Author by
user7434041
Updated on June 28, 2022Comments
-
user7434041 almost 2 years
var enums = { '1': 'HELLO', '2' : 'BYE', '3' : 'TATA' };
I want to be able to convert that into an array that looks like this,
[ { number:'1', word:'HELLO' }, { number:'2', word:'BYE' }, { number:'3', word:'TATA' } ]
all of the solutions I see form an array of either the keys or the values.