【问题标题】:Javascript - Pulling specific objects out of an arrayJavascript - 从数组中提取特定对象
【发布时间】:2016-02-05 01:05:25
【问题描述】:

编码和学习 javascript 和 node.js 的新手。我在这里有一个包含 50 个图像结果的数组:http://mistakes.io/#6204f3edd56b8891075d

我正在尝试提取该数组中的两个特定对象:“MediaUrl”和“SourceUrl”。

例如,我可以通过body.d.results[15].MediaUrl 提取单个结果,但是如何提取所有 50 个 MediaUrl 或 SourceUrl?我在想我可以通过 for-in 循环来实现这一点,但不清楚如何做到这一点。目标是将这些对象拉出,然后能够从这些特定元素中随机挑选。我是否必须首先创建一个带有 var myArray = ["body.d.results[0].MediaUrl", body.d.results[1].MediaUrl", body.d.results[3].MediaUrl", ...] 之类的数组的变量?

非常感谢任何帮助。我一直在搜索示例和教程,但不知道如何表达我正在寻找的内容。我相信这个问题与这里不同:From an array of objects, extract value of a property as array 因为它也没有解释如何随机选择。

【问题讨论】:

  • 既然你把它们放在一个完美的功能数组中,为什么不简单地像这样随机选择:body.d.results[Math.floor(Math.random() * body.d.results.length)].MediaUrl?将它们取出并将它们分成不同的数组似乎没有必要。
  • 另外,重复的问题。 stackoverflow.com/questions/19590865/…

标签: javascript arrays node.js


【解决方案1】:

如果您想将它们全部存储在自己的数组中,您可以轻松地遍历数组并将结果分配给新数组:

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

这将为您提供两个数组,其中包含值。现在,对于随机挑选,您可以执行以下操作:

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

上面将为您提供一个介于 0 和数组长度之间的整数(由于Math.floor,不包括数组长度本身(这很有用,因为在数组的长度索引处实际上没有项目,这可能会带来麻烦否则!))现在你可以把这个随机值从你的数组中拉出来:

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

但比这更容易的是简单地将所有 结果 打包到一个变量中,然后从那里开始 - 因为它已经在内存中,所以不需要复制你已经拥有的数据!

var array = body.d.results;
var randomIndex = Math.floor(Math.random() * array.length);
console.log('src:', array[randomIndex].SourceUrl, 'media:', array[randomIndex].Media)

【讨论】:

  • 非常感谢您在这里分享所有这些选项!似乎最符合我想要实现的目标。事实上,每个人的回答和建议都是绝对有帮助的,尤其是从学习的角度来看。谢谢!
【解决方案2】:

要提取MediaUrls 的数组,请通过map 调用运行它:

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

由于map“创建一个新数组,其结果是对该数组中的每个元素调用提供的函数”,返回的是这个数组:

["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", ...]

片段(使用 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"];
}));

【讨论】:

    【解决方案3】:

    这就是我会做的方式。

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

    无论何时你想要一个随机值getFromArray(newArray)

    【讨论】:

    • 我不会使用getFromArray,而是使用getRandomFromArray 之类的东西。这是一个挑剔的问题,但我最近一直在关注。
    • 完全有道理。要么我应该提供洗牌的数组,要么我应该重命名它。感谢您的反馈。
    猜你喜欢
    • 2018-09-18
    • 1970-01-01
    • 2015-07-13
    • 1970-01-01
    • 1970-01-01
    • 2020-06-09
    • 2020-10-02
    • 2021-05-15
    • 1970-01-01
    相关资源
    最近更新 更多