Home > Back-end >  How to convert an array of indexed objects to a plain object
How to convert an array of indexed objects to a plain object

Time:05-06

How to convert an array of this type:

place:
[
     {
         "_id": "xxxxx",
         "loc": [
             0: "xxx",
             1: "xxx"
         ]
     }
]

To something like this:

place:
{
  lat: "xxx"
  lng: "xxx"
  _id: "xxxxx"
}

Using javascript, I tried something like

let object = {};

place.forEach(element => {
     object[element[0]] = element[1];
});

but it did not work for me, I am using angular to make a method and I need to convert the array of objects that I am showing

CodePudding user response:

Assuming the totally invalid

"loc": [
    0: "xxx",
    1: "xxx"
]

is actually just

"loc": [
    "xxx",
    "xxx"
]

let place =
[
     {
         "_id": "xxxxx",
         "loc": [
             "xxx",
             "xxx"
         ]
     }
]

let { _id, loc: [lat, lng]} = place[0];
let output = { _id, lat, lng};
console.log(output);

  • Related