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.

4
  • Simply use map on array to transform them: const output = country.map(c => [c.country, c.visits]) Commented Mar 18, 2020 at 12:35
  • Use the first link to get your 2nd, 3rd and 4th arrays. Use the second link to get the keys from one of your objects - country[0] for example. Commented Mar 18, 2020 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); Commented Mar 18, 2020 at 12:56
  • Your answer solved my issue.Thank you. Commented Mar 18, 2020 at 13:39

1 Answer 1

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; }

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.