【问题标题】:Applying a method to JavaScript object on the fly动态地将方法应用于 JavaScript 对象
【发布时间】:2017-11-30 06:52:46
【问题描述】:

我有一个动态加载的对象,控制台中JSON.stringify() 的打印如下所示:

var data = [
    {
        "attributes": {
            "OBJECTID": 1046
        },
        "geometry": {
            "x": -9814734.1764,
            "y": 5130578.545900002
        }
    },
    {
        "attributes": {
            "OBJECTID": 1051
        },
        "geometry": {
            "x": -9814335.3286,
            "y": 5130497.9344
        }
    },
    {
        "attributes": {
            "OBJECTID": 1052
        },
        "geometry": {
            "x": -9814639.1784,
            "y": 5130583.1822
        }
    },
    {
        "attributes": {
            "OBJECTID": 1053
        },
        "geometry": {
            "x": -9814496.7964,
            "y": 5130560.822300002
        }
    }
];

如何将.toFixed(2) 函数应用于geometry 节点中的XY 中的每一个?

【问题讨论】:

标签: javascript jquery


【解决方案1】:

你需要使用map函数:

const formattedData = data.map(d => {
  d.geometry.x = parseFloat(d.geometry.x).toFixed(2);
  d.geometry.y = parseFloat(d.geometry.y).toFixed(2);

  return d;
})

如果您不想覆盖原始数据,请随意更改属性名称 (x -> xFormatted)。

【讨论】:

  • 不幸的是,Gurvinder 以 30 秒的优势击败了你
【解决方案2】:

使用map

data = data.map( function(s){
  s.geometry.x = s.geometry.x.toFixed(2);
  s.geometry.y = s.geometry.y.toFixed(2);
  return s;
})

编辑

forEach

data.forEach( function(s){
  s.geometry.x = s.geometry.x.toFixed(2);
  s.geometry.y = s.geometry.y.toFixed(2);
})

【讨论】:

  • 我认为这里不需要.maps 是一个对象,所以无论如何它都会改变数组中的原始对象。
【解决方案3】:

试试这个

//Your Data
var data = [
    {
        "attributes": {
            "OBJECTID": 1046
        },
        "geometry": {
            "x": -9814734.1764,
            "y": 5130578.545900002
        }
    },
    {
        "attributes": {
            "OBJECTID": 1051
        },
        "geometry": {
            "x": -9814335.3286,
            "y": 5130497.9344
        }
    },
    {
        "attributes": {
            "OBJECTID": 1052
        },
        "geometry": {
            "x": -9814639.1784,
            "y": 5130583.1822
        }
    },
    {
        "attributes": {
            "OBJECTID": 1053
        },
        "geometry": {
            "x": -9814496.7964,
            "y": 5130560.822300002
        }
    }
];


//Updating data 
data.forEach(function(item,index){
  item["geometry"]["x"]=item["geometry"]["x"].toFixed(2);
  item["geometry"]["y"]=item["geometry"]["y"].toFixed(2);
})

console.log(JSON.stringify(data))

【讨论】:

    【解决方案4】:

    只需使用 forEach 函数进行迭代。还要确保在调用toFixed 函数之前使用parseFloat 解析值。

    data.forEach(entry => {
        entry.geometry.x = parseFloat(entry.geometry.x).toFixed(2);
        entry.geometry.y = parseFloat(entry.geometry.y).toFixed(2);
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-06-06
      • 1970-01-01
      • 2012-03-27
      • 2012-04-08
      • 1970-01-01
      • 2010-11-10
      • 1970-01-01
      相关资源
      最近更新 更多