【问题标题】:Javascript: Accessing Property of Objects Inside an ArrayJavascript:访问数组内对象的属性
【发布时间】:2014-06-09 23:05:55
【问题描述】:

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

变量数据集1 = [ {video_name:“苹果”,video_views:100}, {video_name:“橙子”,video_views:35}, {video_name:“葡萄”,video_views:20}, {video_name:“鳄梨”,video_views:85}, {video_name:“西红柿”,video_views:60} ]

【问题讨论】:

  • dataset1[0].video_views
  • 你能给我们更多的背景信息吗?目前还不清楚。
  • @theg435 我想使用 video_views 作为使用 d3.js 绘制折线图的 y 值。完整问题请参见此处:stackoverflow.com/questions/24128512/…

标签: javascript


【解决方案1】:

dataset1[0].video_views 会明白的

【讨论】:

    【解决方案2】:

    您在此处处理一组对象。因此,应该可以在 javascript 中使用数组的 forEach() 方法。您可以在MD5 Documentation中阅读更多相关信息

    以下代码 sn-p 应该遍历您的对象数组并轻松访问 key: value 对。

    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}
            ]
    
    dataset1.forEach(function (element, index, array){
    console.log("Video Name: " + dataset1[index].video_name + "; Views: "+ dataset1[index].video_views);
    });

    【讨论】:

      【解决方案3】:

      如果您希望根据视频名称查看视频,则需要遍历数组并找到它。

      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 这样的库来做同样的事情,但不必查看循环。

      【讨论】:

        猜你喜欢
        • 2013-12-02
        • 2019-10-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-29
        • 1970-01-01
        相关资源
        最近更新 更多