0

How to convert the below json into

var body = [{id:1,Country:'Denmark',price: 7.526,Location:'Copenhagen'},
    {id:2, Country:'Switzerland', price:7.509, Location:'Bern'},
  ]

From above json into array of array as like below.

varbody = [
    [1, 'Denmark', 7.526, 'Copenhagen'],
    [2, 'Switzerland', 7.509, 'Bern'],
    [3, 'Iceland', 7.501, 'Reykjavík'],
    [4, 'Norway', 7.498, 'Oslo'],
  ]
  • 1
    Please take note that this is not a JSON, but a Javascript Object. JSON are strings – Cid Oct 11 '20 at 09:44
  • @Cid: _"JSON are strings"_ - could you please elaborate? What is JSON in first place? How is _it_ a string? – ruth Oct 11 '20 at 10:19
  • @MichaelD https://stackoverflow.com/questions/3975859/what-are-the-differences-between-json-and-javascript-object – Anusha kurra Oct 11 '20 at 10:21

2 Answers2

1

You could destructure the objects and get an array with the wanted order of the elements.

const
    body = [{ id: 1, Country: 'Denmark', price: 7.526, Location: 'Copenhagen' }, { id: 2, Country: 'Switzerland', price: 7.509, Location: 'Bern' }],
    result = body.map(({ id, Country, price, Location }) => [id, Country, price, Location]);
  
console.log(result);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

Use the Array#map to map each object and Object#values to transform each object to the array of the object's values:

const body = [{id:1,Country:'Denmark',price: 7.526,Location:'Copenhagen'}, {id:2, Country:'Switzerland', price:7.509, Location:'Bern'}];
const output = (arr) => arr.map(Object.values);

console.log(output(body));
Fullstack Guy
  • 16,368
  • 3
  • 29
  • 44