0

I have a scenario while working for charts where i need to convert the below array of objects into other array of arrays.

Inputs

const country = [
  {"country": "Germany","visits": "306"},
  {"country": "USA","visits": "106"},
  {"country": "UK","visits": "206"},
];

and the desired output should look like below::

[
          ["Country", "Visits"],
          ["Germany", 306],
          ["USA", 106],
          ["UK", 206]
]

I am unable to get this desired output.

user12893845
  • 176
  • 2
  • 13
  • Simply use `map` on array to transform them: `const output = country.map(c => [c.country, c.visits])` – nbokmans Mar 18 '20 at 12:35
  • Use the [first link](https://stackoverflow.com/questions/55041867/convert-an-array-of-objects-to-array-of-the-objects-values) to get your 2nd, 3rd and 4th arrays. Use the [second link](https://stackoverflow.com/questions/8763125/get-array-of-objects-keys) to get the keys from one of your objects - `country[0]` for example. – Nick Parsons Mar 18 '20 at 12:39
  • 1
    Well i prepared an answer, but when i was ready the question was closed, here is it using reduce... `const country = [ { country: 'Germany', visits: '306' }, { country: 'USA', visits: '106' }, { country: 'UK', visits: '206' }, ]; const reducer = (acc, curr, idx, self) => { const result = acc; result.push([curr.country, curr.visits]) if (idx === self.length - 1) { const keys = Object.keys(curr); result.unshift(keys); } return result; } const result = country.reduce(reducer, []) console.log(result);` – JuanDM Mar 18 '20 at 12:56
  • Your answer solved my issue.Thank you. – user12893845 Mar 18 '20 at 13:39

1 Answers1

1

All you need to do is map the fields to an array.

const countries = [
  { "country": "Germany", "visits": "306" },
  { "country": "USA",     "visits": "106" },
  { "country": "UK",      "visits": "206" },
];

console.log(countries.map(country => [ country.country, country.visits ]));
.as-console-wrapper { top: 0; max-height: 100% !important; }

If you want all the values, just use Object.values.

const countries = [
  { "country": "Germany", "visits": "306" },
  { "country": "USA",     "visits": "106" },
  { "country": "UK",      "visits": "206" },
];

console.log(countries.map(country => Object.values(country)));
.as-console-wrapper { top: 0; max-height: 100% !important; }
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132