0

Hey I got this object inside polygons.js:

var polygons = [
  {
    "_id" : "12345",
    "geometry" : {
       "coordinates" : [[
           [9.123553, 48.71568],
           [ 9.119548, 48.71526 ]
       ]]
    }
  },
  {
    "_id" : "67890",
    "geometry" : {
       "coordinates" : [[
           [ 9.090445, 48.715736 ],
           [ 9.089583, 48.715687 ]
       ]]
    }
  }
]

I want to loop through this array in order to get a result like this:

[
  { 
    "_id" : "12345",
    "coordinates" : [[
      [9.123553, 48.71568],
      [ 9.119548, 48.71526 ]  
    ]]
  },
  { 
    "_id" : "67890",
    "coordinates" : [[
      [ 9.090445, 48.715736 ],
      [ 9.089583, 48.715687 ]  
    ]]
  }
]

Does anyone have an idea how to solve it? Thank you very much in regard!

1
  • Look into Array.map. Commented Sep 26, 2018 at 19:16

3 Answers 3

1

you can map through the array and make the changes you need

formatted_polygons = polygons.map(function(polygon){
    return {
        coordinates : polygon.geometry.coordinates,
        _id : polygon._id
    }
});
Sign up to request clarification or add additional context in comments.

4 Comments

when I run the code, it gets me this output: { _id: '12345', coordinates: [ [Array] ] }, { _id: '67890', coordinates: [ [Array] ] }
What functionality of polygon.js are you trying to use ?
I want to prepare a rest api endpoint that returns the data like this. polygon.js is a json dump I have to use
Have you tried JSON.stringify( formatted_polygons ) ?
0

Seems like you're just trying to get rid of the "geometry" prop and get the "coordinates" directly?

polygons.map(polygon => ({ _id: polygon._id, coordinates: polygon.geometry.coordinates }))

Should achieve what you're looking for

Comments

0

You can simply use Array.map():

var polygons = [ { "_id" : "12345", "geometry" : { "coordinates" : [[ [9.123553, 48.71568], [ 9.119548, 48.71526 ] ]] } }, { "_id" : "67890", "geometry" : { "coordinates" : [[ [ 9.090445, 48.715736 ], [ 9.089583, 48.715687 ] ]] } } ];

let result = polygons.map(({_id,geometry})=>Object.assign({},{_id, coordinates :geometry.coordinates}));
console.log(result);

2 Comments

Thanks for your solution, when I run this code cannot see whats inside the coordinates-array. it only logs this: [ { _id: '12345', coordinates: [ [Array] ] }, { _id: '67890', coordinates: [ [Array] ] }] I had this issue before, I still can't resolve it
@LeaHontiveros is there any adjacent to the coordinates, if it is there than please click on the arrow to expand the array. You will be able to see the elements of the array after that. :-) and please mark as accepted if it worked for you.

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.