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.
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)
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; }
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);
Need to create an object of Map type then get the value using get method like outData.get("1")
var obj = {
'1': 'HELLO',
'2': 'BYE',
'3': 'TATA'
};
var outData = new Map();
Object.keys(obj).forEach(function (e) {
outData.set(e, obj[e])
});
To get data use outData.get("key")
Now the out put data will like-
Map(3) {"1" => "HELLO", "2" => "BYE", "3" => "TATA"}
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;}
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.