0

How to convert this format into an Array. im getting a keyValue pair as below and I have to turn this format to an array in .TS file

countryNew: 
{
IN: 159201 
BD: 82500
PK: 14237
UA: 486
RU: 9825
}

to This...

countryNew: [ 
{countryCode: 'IN' , value : 159201}, 
{countryCode: 'BD' , value : 82500}, 
{countryCode: 'PK' , value : 14237}, 
{countryCode: 'UA' , value : 486}, 
{countryCode: 'RU' , value : 9825},
]

3 Answers3

2

Object can be easily converted to an array with the help Object.keys() and Array.prototype.map() methods

const countryNew = {
  IN: 159201,
  BD: 82500,
  PK: 14237,
  UA: 486,
  RU: 9825,
};

const result = Object.keys(countryNew)
  .map(key => ({ countryCode: key, value: countryNew[key] }));

console.log(result);
yurzui
  • 205,937
  • 32
  • 433
  • 399
  • Why reallocate the array for each and every property? IMHO this is meant more to increase the entropy of the universe, than to solve the actual problem. :D – Alberto Chiesa Mar 30 '21 at 13:54
  • @A.Chiesa For such small objects I don't think it's time to think about microoptimization. – yurzui Mar 30 '21 at 13:56
  • It's not a matter of micro-optimization. You have map, that would not reallocate the array every single time, so you should use it over reduce. Using reduce uses "more" code, more CPU time, (possibly) a lot more memory, for the same result. You don't know if the object has 5 or 500 properties. Just the possibility of allocating hundreds of useless arrays, copied over and over, gives me an headache. Why go O(n^2) if you can go O(n) YMMV. – Alberto Chiesa Mar 30 '21 at 14:01
  • 1
    @A.Chiesa you're right. I over-engineered it first. – yurzui Mar 30 '21 at 14:09
2

Try using Object.keys and Array.map like this:

const countries = Object.keys(countryNew).map((country) => {
   return {countryCode: country, value: countryNew[country]}
})
Ahsan Naveed
  • 104
  • 7
2

Try using Object.entries:

const countryNew = {
  IN: 159201,
  BD: 82500,
  PK: 14237,
  UA: 486,
  RU: 9825,
};

const result = Object.entries(countryNew).map(entry => ({countryCode: entry[0] , value : entry[1]}));

console.log(result);
Alberto Chiesa
  • 7,022
  • 2
  • 26
  • 53