使用“geom”键获取值的下划线

时间:2016-02-11 10:27:17

标签: javascript underscore.js

我有这个对象数组。

[ { geom: '{"type":"Point","coordinates":[-3.81086160022019,50.4619066354793]}' },
  { geom: '{"type":"Point","coordinates":[-4.038333333,51.17166667]}' },
  { geom: '{"type":"Point","coordinates":[-4.286666667,50.99666667]}' },
  { geom: '{"type":"Point","coordinates":[-4.006666667,51.11833333]}' },
  { geom: '{"type":"Point","coordinates":[-3.155,50.75333333]}' } ]

我希望没有geom:离开我

[ {"type":"Point","coordinates":[-3.81086160022019,50.4619066354793]},
  {"type":"Point","coordinates":[-4.038333333,51.17166667]},
  {"type":"Point","coordinates":[-4.286666667,50.99666667]},
  {"type":"Point","coordinates":[-4.006666667,51.11833333]},
  {"type":"Point","coordinates":[-3.155,50.75333333]}]

这可以用下划线完成吗?

2 个答案:

答案 0 :(得分:2)

您也可以在没有underscore的情况下执行此操作。您只需循环数组并返回currentObj.geom。此外,currentObj.geom是一个字符串,因此您需要JSON.parse



var a = [ { geom: '{"type":"Point","coordinates":[-3.81086160022019,50.4619066354793]}' },
  { geom: '{"type":"Point","coordinates":[-4.038333333,51.17166667]}' },
  { geom: '{"type":"Point","coordinates":[-4.286666667,50.99666667]}' },
  { geom: '{"type":"Point","coordinates":[-4.006666667,51.11833333]}' },
  { geom: '{"type":"Point","coordinates":[-3.155,50.75333333]}' } ]


var result = a.map(function(item){
  return JSON.parse(item.geom);
});

document.write("<pre>" + JSON.stringify(result,0,4) + "</pre>");
&#13;
&#13;
&#13;

答案 1 :(得分:1)

正如 @Rajesh 所述,此处不需要下划线,但如果您真的想使用它,那么就可以: -

var data = [ { geom: '{"type":"Point","coordinates":[-3.81086160022019,50.4619066354793]}' },
             { geom: '{"type":"Point","coordinates":[-4.038333333,51.17166667]}' },
             { geom: '{"type":"Point","coordinates":[-4.286666667,50.99666667]}' },
             { geom: '{"type":"Point","coordinates":[-4.006666667,51.11833333]}' },
             { geom: '{"type":"Point","coordinates":[-3.155,50.75333333]}' } ];

var vals = _.map(data, function(obj){
   return JSON.parse(obj.geom);
});