1

I have this object:

[
   {
     "latitude": "113.232160114",
     "longitude": "-1.786978559"
   },
   {
     "latitude": "113.211955085",
     "longitude": "-1.790031776"
   }
]

is there any possible way to make it look like this using JavaScript?

[
   [
      113.232160114,
      -1.786978559
   ],
   [
      113.211955085,
      -1.790031776
   ]
]
brown26
  • 89
  • 1
  • 3
  • 10
  • 1
    No, since the second one is not valid JavaScript. An object (indicated by curly brackets) consists of pairs of keys and values, and it is not possible to omit a key. Do you mean `[[113.232160114, -1.786978559], [113.211955085, -1.790031776]]` (with square brackets, indicating an array)? – Amadan Nov 04 '22 at 02:46
  • @Amadan yup, sorry.. I updated my question – brown26 Nov 04 '22 at 02:48
  • 1
    If `a` is your initial array of objects, it's as simple as `a.map(Object.values)` – kikon Nov 04 '22 at 02:50
  • @kikon I was just about to answer with that :) but you should post it as an answer. – Zac Anger Nov 04 '22 at 02:50
  • Since you change an object to an array, please note that objects didn't guarantee the order of their keys before ES2015; I'd recommend reviewing [this post](https://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order). – kikon Nov 04 '22 at 02:57

2 Answers2

3

Yes, with one single line, and two built-in functions: Array.prototype.map produces an array obtained by applying a function to each element of an array, and Object.values produces a list of enumerable properties of an object.

const data = [
   {
     "latitude": "113.232160114",
     "longitude": "-1.786978559"
   },
   {
     "latitude": "113.211955085",
     "longitude": "-1.790031776"
   }
];

const result = data.map(Object.values);
console.log(result);
Amadan
  • 191,408
  • 23
  • 240
  • 301
  • Nice approach, but it relies on the keys to be ordered correctly – Andrew Parks Nov 04 '22 at 02:52
  • @AndrewParks Yes. However, given the literal object expression in OP, the order is guaranteed (since ES2015). Good to point out though, in case the object is constructed in some other way. – Amadan Nov 04 '22 at 02:53
1

const a = [
  { latitude: '113.232160114', longitude: '-1.786978559' },
  { latitude: '113.211955085', longitude: '-1.790031776' }
];
console.log(a.map(({latitude:i, longitude:j})=>[i,j]));
Andrew Parks
  • 6,358
  • 2
  • 12
  • 27
  • 1
    Although ES2015 does guarantee the order of keys, it really depends on the context and source of the data (e.g., an ajax response + `JSON.parse`). This answer seems to me **much safer** than the accepted answer that was also my earlier suggestion (in a comment -`a.map(Object.values)` ) – kikon Nov 04 '22 at 03:08