将对象数组中的字符串转换为数字数组

时间:2016-08-15 05:25:09

标签: javascript angularjs json

我有一个对象数组,其中一些属性作为字符串值,有人可以帮我从中获取数字。这是数组的样子。

  scores = [
               {
                  maxScore:"100"
                  obtainedScore:"79"
                  passed:"pass"
                  subject:"Maths"
               },
               {
                  maxScore:"100"
                  obtainedScore:"73"
                  passed:"pass"
                  subject:"Science"
               },
               {
                  maxScore:"100"
                  obtainedScore:"82"
                  passed:"pass"
                  subject:"English"
               }
           ]

我希望获得的分数 maxScore 应从这些对象中取出并将它们放在两个不同的数组中

我试过这个

for (var  i =0 ; i < score.length; i++)
{ 
   var marks[i] = parseInt(score[i].obtainedScore) ;
} 

我找到了NaN。

2 个答案:

答案 0 :(得分:1)

  1. 基于您的尝试的正确回答

    &#13;
    &#13;
        var scores = [{
          maxScore: "100",
          obtainedScore: "79",
          passed: "pass",
          subject: "Maths"
        }, {
          maxScore: "100",
          obtainedScore: "73",
          passed: "pass",
          subject: "Science"
        }, {
          maxScore: "100",
          obtainedScore: "82",
          passed: "pass",
          subject: "English"
        }]
        var marks = [];
        for (var i = 0; i < scores.length; i++) {
          marks[i] = parseInt(scores[i].obtainedScore, 10);
        }
        console.log(marks)
    &#13;
    &#13;
    &#13;

  2. MY SOLN (在您尝试编辑之前)

  3. &#13;
    &#13;
    var scores = [{
          maxScore: "100",
          obtainedScore: "79",
          passed: "pass",
          subject: "Maths"
        }, {
          maxScore: "100",
          obtainedScore: "73",
          passed: "pass",
          subject: "Science"
        }, {
          maxScore: "100",
          obtainedScore: "82",
          passed: "pass",
          subject: "English"
        }]
    
        function decoupler(arr, prop) {
          return arr.map(function(item, index) {
            return parseInt(item[prop], 10);
          });
        }
        var arr1 = decoupler(scores, "maxScore");
        var arr2 = decoupler(scores, "obtainedScore");
    
        console.log(arr1);
        console.log(arr2);
    &#13;
    &#13;
    &#13;

    修改:根据comment by jfriend00parseInt()添加了基数参数。

答案 1 :(得分:0)

我不是100%确定你想要输出的是什么,但是:

  

我希望获得的分数和maxScore应该从这些中取出   对象并将它们放在两个不同的数组中

var arrScore = [],
        arrMax = [];

    scores.forEach(i => {
        arrScore.push(!isNaN(parseInt(i.obtainedScore)) ? parseInt(i.obtainedScore) : 0);
        arrMax.push(!isNaN(parseInt(i.maxScore)) ? parseInt(i.maxScore) : 0);
    });

基本上,这会创建两个数组arrScore,其中包含每个单独的分数值,arrMax包含最大分数数组。

使用forEach函数,我们迭代数组并将值推送到各自的数组中。请注意,我们还要确保类型是有效的整数。