2
votes

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

3
dataset1[0].video_views - chiliNUT
Can you give us more context? It's quite unclear at the moment. - georg
@theg435 I want to use the video_views as the y-value for drawing a line graph using d3.js. See here for full question: stackoverflow.com/questions/24128512/… - dmr07

3 Answers

0
votes

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.

5
votes

dataset1[0].video_views would get that

2
votes

You are working with an array of objects here. It should, therefore, be possible to use the forEach() method of arrays in javascript. You can read more about this in MD5 Documentation

The following code snippet should iterate through your array of objects and access the key: value pairs easily.

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