如何将$ .each对象转换为数组

时间:2015-01-08 03:00:00

标签: javascript jquery arrays

我有一个json,我$.each videolist并尝试获取second。然后,我希望将second转换为数组[],方便我做下一个我想要的功能。只是不确定如何将其变成数组。



var videoinfo = [{
    "startdatetime": "2014-12-21 00:23:14",
    "totalsecondrun": "2019402310",
    "videolist": [{
        "videoid": "uoSDF234",
        "second": "10"
    }, {
        "videoid": "0apq3ss",
        "second": "14"
    }]
}];


var calduration = function() {

    var list = videoinfo[0].videolist;

    $.each(list, function(index, value) {
        alert($.makeArray(value.second));
    });

};

calduration();

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

我预计输出应为[10,14]。

1 个答案:

答案 0 :(得分:1)

如果您坚持使用$.each()循环,正如标题所暗示的,这是一种方法:

var calduration = function () {
    var duration = [];
    $.each(videoinfo[0].videolist, function (index, value) {
        duration.push(parseInt(value.second, 10));
    });

    return duration;
};

Example Here


我建议使用$.map(),但是:

var calduration = function () {
    return $.map(videoinfo[0].videolist, function (value, index) {
        return parseInt(value.second, 10);
    });
};

..或.map()

return videoinfo[0].videolist.map(function (value, index) {
    return parseInt(value.second, 10);
});

Example Here


如果你想使用普通的JS:

var calduration = function () {
    return Array.prototype.map.call(videoinfo[0].videolist, function(value){
        return parseInt(value.second, 10);
    });
};

Example Here