最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Use underscore to find a value by key - Stack Overflow

programmeradmin0浏览0评论

I have a string that I need to search for within a json object and return back a specific hash number from that found value. I got it to work without underscore, but it's poorly optimized. What I need to do is stop the loop as soon as the fileToSearch string is found.

For example, I have a json object here:

  var json = {
    "images/mike.jpg" : "images/mike.12345.jpg",
    "images/joe.jpg" : "images/joe.axcvas.jpg",
    "images/mary.jpg" : "images/mary.mndfkndf.jpg",
    "images/jane.jpg" : "images/jane.dfad34.jpg",
  };

And I have a variable fileToSearch that I need to look for in the above object.

 var fileToSearch = "joe.jpg";

What should get outputted is the hash value in images/joe.axcvas.jpg, so axcvas.

Without underscore:

  var hash;

  for (var key in json) {
    var index = key.indexOf(fileToSearch);
    if (index !== -1) {
      hash = json[key].split('.')[1];
    }
  }
  console.log(hash); //axcvas

How can I optimize/achieve this with Underscore?

I have a string that I need to search for within a json object and return back a specific hash number from that found value. I got it to work without underscore, but it's poorly optimized. What I need to do is stop the loop as soon as the fileToSearch string is found.

For example, I have a json object here:

  var json = {
    "images/mike.jpg" : "images/mike.12345.jpg",
    "images/joe.jpg" : "images/joe.axcvas.jpg",
    "images/mary.jpg" : "images/mary.mndfkndf.jpg",
    "images/jane.jpg" : "images/jane.dfad34.jpg",
  };

And I have a variable fileToSearch that I need to look for in the above object.

 var fileToSearch = "joe.jpg";

What should get outputted is the hash value in images/joe.axcvas.jpg, so axcvas.

Without underscore:

  var hash;

  for (var key in json) {
    var index = key.indexOf(fileToSearch);
    if (index !== -1) {
      hash = json[key].split('.')[1];
    }
  }
  console.log(hash); //axcvas

How can I optimize/achieve this with Underscore?

Share Improve this question asked Apr 20, 2016 at 19:08 cusejuicecusejuice 10.7k27 gold badges95 silver badges150 bronze badges 1
  • Heck, you don't even need filter. Just throw a break in after you find your hash and it's pretty optimal already. – Hamms Commented Apr 20, 2016 at 19:11
Add a ment  | 

2 Answers 2

Reset to default 5

You can use _.findKey in such way:

var key = _.findKey(json, function(value, key) {
    return key.indexOf(fileToSearch) >= 0;
});
var hash = key? json[key].split('.')[1] : undefined;

Note that this method is available since v1.8.0.

You can break the loop when you find the element

 var hash;

 for (var key in json) {
     var index = key.indexOf(fileToSearch);
     if (index !== -1) {
       hash = json[key].split('.')[1];
       break;
     }
 }
 console.log(hash);
发布评论

评论列表(0)

  1. 暂无评论