admin管理员组文章数量:1356582
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 abreak
in after you find your hash and it's pretty optimal already. – Hamms Commented Apr 20, 2016 at 19:11
2 Answers
Reset to default 5You 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);
本文标签: javascriptUse underscore to find a value by keyStack Overflow
版权声明:本文标题:javascript - Use underscore to find a value by key - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744046428a2581610.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论