Javascript:访问数组内部对象的属性 [英] Javascript: Accessing Property of Objects Inside an Array

查看:42
本文介绍了Javascript:访问数组内部对象的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从下面的数据集1中获取整数"100"?

How can I get the integer "100" from dataset1 [below]?



    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}
        ]

推荐答案

如果要基于视频名称观看视频,则需要遍历数组并找到它.

If you want video views based on video name, you'll need to loop through the array and find it.

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);

或者您可以使用下划线之类的库来执行相同的操作,而无需查看循环

or you could use a library like Underscore to do the same thing, but without having to look at the loop.

这篇关于Javascript:访问数组内部对象的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆