Javascript:访问数组内对象的属性

时间:2014-06-09 23:05:55

标签: javascript

如何从dataset1 [下面]获取整数“100”?


    var dataset1 = [ 
            {video_name: "Apples", video_views: 100},
            {video_name: "Oranges", video_views: 35},
            {video_name: "Grapes", video_views: 20},
            {video_name: "Avocados", video_views: 85},
            {video_name: "Tomatoes", video_views: 60}
        ]

3 个答案:

答案 0 :(得分:4)

dataset1[0].video_views会得到那个

答案 1 :(得分:0)

如果您想要基于视频名称的视频观看,则需要循环播放数组并找到它。

var dataset1 = [ 
    {video_name: "Apples", video_views: 100},
    {video_name: "Oranges", video_views: 35},
    {video_name: "Grapes", video_views: 20},
    {video_name: "Avocados", video_views: 85},
    {video_name: "Tomatoes", video_views: 60}
]

var searchCriteria = {video_name: "Apples"};
var searchResult;

//This loop sets searchResult to the LAST element in the set that meets the criteria

dataset1.forEach(function(obj){
    var matches = true;
    for (var key in searchCriteria){
        if (searchCriteria[key] !== obj[key]){
            matches = false;
        }
    }
    if (matches){
        searchResult = obj;
    }
});

console.log(searchResult);

或者您可以使用像Underscore这样的库来做同样的事情,但不必查看循环。

答案 2 :(得分:0)

您正在使用一组对象。因此,应该可以在javascript中使用数组的forEach()方法。您可以在MD5 Documentation

中详细了解相关信息

以下代码段应遍历您的对象数组并轻松访问键:值对。



active