简体   繁体   中英

How do I access the property of an object that is a string?

I have an object which I need to convert from a string to a float in a before hook:

{ '$near': 
   { '$geometry': { type: 'Point', coordinates: [Array] },
     '$minDistance': '0',
     '$maxDistance': '10000'
   }
}

How do I access the $near property if its a string? I need to convert the values inside 'coordinates' from a string to a float.

console.log(location['$near']);

Doesn't work

This should work:

let thelocation = { '$near': 
   { '$geometry': { type: 'Point', coordinates:  [ "144.982", "-37.864" ] },
     '$minDistance': '0',
     '$maxDistance': '10000'
   }
};
let coords = [parseFloat(thelocation.$near.$geometry.coordinates[0]),
              parseFloat(thelocation.$near.$geometry.coordinates[1])];
console.log(coords);

Output:

Array [ 144.982, -37.864 ]

Using vanillaJS you can access the coordinates as below

let location = { '$near': 
   { '$geometry': { type: 'Point', coordinates: [{pointX: "1.23", pointY: "4.56"}] },
     '$minDistance': '0',
     '$maxDistance': '10000'
   }
}

location['$near']['$geometry']['coordinates'] //[{"x":"1.23","y":"4.56"}]

location['$near']['$geometry']['coordinates'].forEach(cor =>{
    console.log(cor.pointX);
  console.log(cor.pointY)
})

location is generally reserved to the browser. Try using another variable name. Also, keys in an object are all strings, so there's no special way of accessing it, other than the method you've already used (key-accessor or dot-notation):

 let _location = { '$near': { '$geometry': { type: 'Point', coordinates: [1,2] }, '$minDistance': '0', '$maxDistance': '10000' } } console.log(_location['$near']['$geometry']['coordinates']); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM