-1

New to coding & learning javascript & node.js. I have an array of 50 image results here: http://mistakes.io/#6204f3edd56b8891075d

I am trying to pull out two specific objects in that array: "MediaUrl" and "SourceUrl".

I can pull out an individual result via body.d.results[15].MediaUrl for example, but how do I pull out all 50 MediaUrl or SourceUrl? I was thinking that I could achieve this with a for of for-in loop but unclear how to do so. The goal is to pull those objects out and then be able to pick randomly from those specific elements. Would I first have to create a variable with an array like var myArray = ["body.d.results[0].MediaUrl", body.d.results[1].MediaUrl", body.d.results[3].MediaUrl", ...] ?

Any help is greatly appreciated. I have been searching up and down for examples and tutorials but not sure how to phrase what I am looking for. I believe this question is different than here: From an array of objects, extract value of a property as array because it doesn't explain how to pick randomly as well.

Community
  • 1
  • 1
mmryspace
  • 689
  • 1
  • 9
  • 18
  • 3
    Since you have them in a perfectly functional array, why not simply randomly pick like this: `body.d.results[Math.floor(Math.random() * body.d.results.length)].MediaUrl`? Taking them out and separating them into a different array seems needless here. – somethinghere Feb 04 '16 at 16:40
  • 1
    Also, duplicate question. http://stackoverflow.com/questions/19590865/from-an-array-of-objects-extract-value-of-a-property-as-array – phenxd Feb 04 '16 at 16:47

3 Answers3

0

If you want to store them all in their own array, you can easily just walk through the array and assign the result to a new array:

var mediaUrlResult = [];
var sourceUrlResult = [];
for(var i = 0; i < body.d.result.length; i++){
    mediaUrlResult.push(body.d.result.MediaUrl);
    sourceUrlResult.push(body.d.result.SourceUrl);
}

This will give you two arrays with the values in them. Now, as for random picking, you could do the following:

Math.floor(Math.random() * Array.length)

The above will give you an integer number between 0 and the arrays length (excluding the arrays length itself thanks to Math.floor (this is useful because there isn't actually an item at the array's length index, which could spell trouble otherwise!)) Now you could pull this random value out of your array:

sourceUrlResult[Math.floor(Math.random() * sourceUrlResult.length)];

But easier than this is to simply pack all your results into a single variable, and then start from there - since it is already in memory there is no need to duplicate data you have already!

var array = body.d.results;
var randomIndex = Math.floor(Math.random() * array.length);
console.log('src:', array[randomIndex].SourceUrl, 'media:', array[randomIndex].Media)
somethinghere
  • 16,311
  • 2
  • 28
  • 42
  • 1
    Really appreciate you sharing all of these options here! Seems most in line with what I am trying to achieve. In fact everyone's answers & suggestions are absolutely helpful especially from the standpoint of learning. Thanks! – mmryspace Feb 04 '16 at 17:11
0

To pull out an array of MediaUrls, run it through a map call:

var mediaUrls = arr.map(function (x) {
    return x["MediaUrl"];
});

Since map "creates a new array with the results of calling a provided function on every element in this array", returned is this array:

["http://4.bp.blogspot.com/-rshrTkUD4Do/TV6mxlXoUxI/AAAAAAAAACw/6kb0msv26iA/s1600/Tina+Modotti.jpg", "http://media-cache-ec0.pinimg.com/736x/ee/cf/5f/eecf5f6d5e776104548f542bd269f631.jpg", ...]

Snippet (using a shortened version of your JSON):

var d = [{
  "__metadata": {
    "uri": "https://api.datamarket.azure.com/Data.ashx/Bing/Search/v1/Image?Query='Photography by tina modotti'&ImageFilters='Size:Large'&$skip=0&$top=1",
    "type": "ImageResult"
  },
  "ID": "acedb185-cc7e-4da8-89be-bd107f4a6528",
  "Title": "tina modotti biography from profots com tina modotti was a remarkable ...",
  "MediaUrl": "http://4.bp.blogspot.com/-rshrTkUD4Do/TV6mxlXoUxI/AAAAAAAAACw/6kb0msv26iA/s1600/Tina+Modotti.jpg",
  "SourceUrl": "http://mastersofphotography.blogspot.com.au/2011/02/tina-modotti.html",
  "DisplayUrl": "mastersofphotography.blogspot.com.au/2011/02/tina-modotti.html",
  "Width": "530",
  "Height": "480",
  "FileSize": "87133",
  "ContentType": "image/jpeg",
  "Thumbnail": {
    "__metadata": {
      "type": "Bing.Thumbnail"
    },
    "MediaUrl": "http://ts2.mm.bing.net/th?id=OIP.M1dd1aa7a5fc5f4b73e1258d402d0f5dbH0&pid=15.1",
    "ContentType": "image/jpg",
    "Width": "480",
    "Height": "434",
    "FileSize": "27551"
  }
}, {
  "__metadata": {
    "uri": "https://api.datamarket.azure.com/Data.ashx/Bing/Search/v1/Image?Query='Photography by tina modotti'&ImageFilters='Size:Large'&$skip=1&$top=1",
    "type": "ImageResult"
  },
  "ID": "5acade4e-106e-49af-b7b4-c3e89fdd2f6d",
  "Title": "Tina Modotti | Indigenous | Pinterest",
  "MediaUrl": "http://media-cache-ec0.pinimg.com/736x/ee/cf/5f/eecf5f6d5e776104548f542bd269f631.jpg",
  "SourceUrl": "http://pinterest.com/pin/393994667370497691/",
  "DisplayUrl": "pinterest.com/pin/393994667370497691",
  "Width": "654",
  "Height": "720",
  "FileSize": "168465",
  "ContentType": "image/jpeg",
  "Thumbnail": {
    "__metadata": {
      "type": "Bing.Thumbnail"
    },
    "MediaUrl": "http://ts4.mm.bing.net/th?id=OIP.M94668199c6351c86fc3d8a8267c19602o2&pid=15.1",
    "ContentType": "image/jpg",
    "Width": "272",
    "Height": "300",
    "FileSize": "11661"
  }
}, {
  "__metadata": {
    "uri": "https://api.datamarket.azure.com/Data.ashx/Bing/Search/v1/Image?Query='Photography by tina modotti'&ImageFilters='Size:Large'&$skip=2&$top=1",
    "type": "ImageResult"
  },
  "ID": "aa661abe-dedc-47c4-a524-fa83e1efbdb2",
  "Title": "Tina Modotti",
  "MediaUrl": "http://www.masters-of-photography.com/images/full/modotti/modotti_roses.jpg",
  "SourceUrl": "http://www.masters-of-photography.com/M/modotti/modotti_roses_full.html",
  "DisplayUrl": "www.masters-of-photography.com/M/modotti/modotti_roses_full.html",
  "Width": "610",
  "Height": "480",
  "FileSize": "78365",
  "ContentType": "image/jpeg",
  "Thumbnail": {
    "__metadata": {
      "type": "Bing.Thumbnail"
    },
    "MediaUrl": "http://ts1.mm.bing.net/th?id=OIP.Maeca6f4759d245091ae2276829dca4efo0&pid=15.1",
    "ContentType": "image/jpg",
    "Width": "300",
    "Height": "236",
    "FileSize": "8950"
  }
}];

console.log(d.map(function(x) {
  return x["MediaUrl"];
}));
Hatchet
  • 5,320
  • 1
  • 30
  • 42
0

This is the way i would do it.

var newArray = body.d.results.map(function(obj){
   return {MediaUrl: obj['MediaUrl'], SourceUrl: obj['SourceUrl']}
});
function getFromRandomArray(array) {
   return array[Math.floor(Math.random() * Array.length)]
}

and whenever you want a random value getFromArray(newArray)

kodvin
  • 1,236
  • 9
  • 14
  • I wouldn't use `getFromArray`, but rather something like `getRandomFromArray`. It's a nitpick but something I've been paying more attention to lately. – somethinghere Feb 04 '16 at 16:58
  • 1
    Totally makes sense. Either i should provide shuffled array or i should rename it. Thanks for the feedback. – kodvin Feb 04 '16 at 17:04