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
   ]
]
5
  • 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)? Commented Nov 4, 2022 at 2:46
  • @Amadan yup, sorry.. I updated my question Commented Nov 4, 2022 at 2:48
  • 1
    If a is your initial array of objects, it's as simple as a.map(Object.values) Commented Nov 4, 2022 at 2:50
  • @kikon I was just about to answer with that :) but you should post it as an answer. Commented Nov 4, 2022 at 2: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. Commented Nov 4, 2022 at 2:57

2 Answers 2

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

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

2 Comments

Nice approach, but it relies on the keys to be ordered correctly
@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.
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]));

1 Comment

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) )

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.