AllJs AllJs - 10 months ago 47
JSON Question

Permute positions of properties in an array of JSON objects with javascript

So I have a massive array of objects that looks like this:

var obj = [
{longitude: lng1, latitude: lat1},
{longitude: lng2, latitude: lat2}

I need a javascript function that allows me to permute the positions of each object's properties within the array like so:

var switchedObj = [
{latitude: lat1, longitude: lng1},
{latitude: lat2, longitude: lng2}

Can someone point me in the right direction?


Answer Source

Here's a working solution. Assuming that we have values for lng1 , lat1 , lng2 and lat2.

Basically lets say we have this object:

var obj = [
{longitude:20, latitude:200}

Then to get the solution you need simple do this. Hope it helps!

var obj = [


var arr1 = [];
var arr2 = [];
var switchedObj = [];
for(var i in obj){
	if(obj[i].hasOwnProperty("longitude") && obj[i].hasOwnProperty("latitude")){
		arr1.push(obj[i]["longitude"]); // 10 and 20
for(var k = 0; k < obj.length; k++){
      latitude: arr2[k],
      longitude: arr1[k]