如何访问作为字符串的对象的属性?

时间:2018-05-24 02:44:57

标签: javascript feathersjs

我有一个对象,我需要在before hook中将字符串转换为float:

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

如果是一个字符串,我如何访问$ near属性?我需要转换里面的坐标'坐标'从字符串到浮点数。

'r'

不能工作

2 个答案:

答案 0 :(得分:1)

这应该有效:

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);

输出:

Array [ 144.982, -37.864 ]

答案 1 :(得分:0)

使用vanillaJS您可以访问以下坐标

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)
})