AllJs AllJs - 8 days ago 6
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?

Thanks.

Answer

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:10,latitude:100},
{longitude:20, latitude:200}
]

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

var obj = [
{longitude:10,
 latitude:100
},

{longitude:20,
 latitude:200
}
]

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
		arr2.push(obj[i]["latitude"]);
	}
}
for(var k = 0; k < obj.length; k++){
      switchedObj.push({
      latitude: arr2[k],
      longitude: arr1[k]
    });
}

console.log(switchedObj);

Comments