AngularJS拆分数组

时间:2018-11-08 09:15:20

标签: javascript angularjs

我有一个看起来像这样的数组

    $scope.A = [

          [ "1.31069258855609,103.848649478524", "1.31138534529796,103.848923050526" ],
          [ "1.31213221536436,103.848328363879", "1.31288473199114,103.849575392632" ]

        ];

我想把它做成这样

        $scope.B = [
           [
             [1.31069258855609,103.848649478524], [1.31138534529796,103.848923050526]
           ],
           [
             [1.31213221536436,103.848328363879], [1.31288473199114,103.849575392632]
           ]
         ];

PS:对不起,如果这不是分裂,我不确定如何解决此问题

代码:

    var latlngs = $scope.polyLineCord.map(subarr => subarr.map(str => str.split(',').map(Number)))
    console.log(latlngs)

enter image description here

2 个答案:

答案 0 :(得分:1)

map外部数组中的每个项目,然后.map每个子数组,split用逗号分隔,map再次Number将字符串转换为数字:

const input = [
  ["1.31069258855609,103.848649478524", "1.31138534529796,103.848923050526"],
  ["1.31213221536436,103.848328363879", "1.31288473199114,103.849575392632"]
];
console.log(
  input.map(
    subarr => subarr.map(
      str => str.split(',').map(Number)
    )
  )
);

答案 1 :(得分:0)

完成这项工作的功能:

function splitMyArray(arr) {
    for (var i = 0; i < arr.length; ++i) {
        var line = arr[i];
        for (var k = 0; k < line.length; ++k) {
            var parts = line[k].split(',');
            line[k] = [parseFloat(parts[0]), parseFloat(parts[1])];
        }
    }
    return arr;
}

用法示例:

var myArr = [
    ["1.31,103.84", "1.32,103.85"],
    ["1.39,103.77", "1.40,103.78"]
];

var splitted = splitMyArray(myArr);
console.log(splitted);