Javascript Lodash : 返回对象的第一个键,其值(即数组)中有一个给定的元素(即字符串)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36959153/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Lodash : return first key of object whose value(i.e Array) has a given element (i.e string) in it
提问by Sandeep Sharma
I have an object like:
我有一个对象,如:
var obj = {
"01": ["a","b"],
"03": ["c","d"],
"04": ["e","c"]
};
and I know an array element ( say "c") of the object key's value then How to find first key value i.e "03" using lodash without using if else?
我知道对象键值的数组元素(比如“c”)然后如何使用 lodash 而不使用 if else 找到第一个键值,即“03”?
I tried like this using lodash and if else:
我尝试这样使用 lodash ,如果其他:
var rId = "";
_.forOwn(obj, function (array, id) {
if (_.indexOf(array, "c") >= 0) {
rId = id;
return false;
}
});
console.log(rId); // "03"
Expected Result: first key i.e "03" if element matches else "".
预期结果:第一个键,即“03”,如果元素匹配其他“”。
After seeing comments:Now I'm also curious to know about
看到评论后:现在我也很想知道
Does I need to go with native javascript(hard to read program in the cases if we use more than 2 if blocks) or lodash way(easily readable program solution in one line)?
我是否需要使用原生 javascript(如果我们使用 2 个以上的 if 块,在这种情况下很难阅读程序)或 lodash 方式(一行易于阅读的程序解决方案)?
回答by Akshat Mahajan
Since you just want a way to be able to find a key using a simple Lodash command, the following should work:
由于您只是想要一种能够使用简单的 Lodash 命令找到密钥的方法,因此以下应该有效:
_.findKey(obj, function(item) { return item.indexOf("c") !== -1; });
or, using ES6 syntax,
或者,使用 ES6 语法,
_.findKey(obj, (item) => (item.indexOf("c") !== -1));
This returns "03" for your example.
这将为您的示例返回“03”。
The predicate function - the second argument to findKey()
- has automatic access to the value of the key. If nothing is found matching the predicate function, undefined
is returned.
谓词函数 - 第二个参数findKey()
- 可以自动访问键的值。如果没有找到与谓词函数匹配的内容,undefined
则返回。
Documentation for findKey()
is here.
对于文档findKey()
是在这里。
Examples taken from the documentation:
从文档中获取的示例:
var users = {
'barney': { 'age': 36, 'active': true },
'fred': { 'age': 40, 'active': false },
'pebbles': { 'age': 1, 'active': true }
};
_.findKey(users, function(o) { return o.age < 40; });
// → 'barney' (iteration order is not guaranteed)
// The `_.matches` iteratee shorthand.
_.findKey(users, { 'age': 1, 'active': true });
// → 'pebbles'
// The `_.matchesProperty` iteratee shorthand.
_.findKey(users, ['active', false]);
// → 'fred'
// The `_.property` iteratee shorthand.
_.findKey(users, 'active');
// → 'barney'
回答by Роман Парадеев
The irony is it is not any harder to implement without any libs.
具有讽刺意味的是,如果没有任何库,实现起来并不困难。
Object.keys(obj).filter(x => obj[x].includes("c"))[0]
回答by Redu
Here comes a single liner answer from the future. Currently only works in Firefox 47 on. Part of ES7 proposal.
这是来自未来的单一班轮答案。目前仅适用于 Firefox 47 上。ES7 提案的一部分。
var obj = {
"01": ["a","b"],
"03": ["c","d"],
"04": ["e","c"]
},
res = Object.entries(obj).find(e => e[1].includes("c"))[0];
document.write(res);
回答by RomanPerekhrest
As an alternative solution: consider native Javascript approach using Object.keys
and Array.some
functions:
作为替代解决方案:考虑使用Object.keys
和Array.some
函数的原生 Javascript 方法 :
var obj = {"01": ["a","b"],"03": ["c","d"],"04": ["e","c"]},
search_str = "c", key = "";
Object.keys(obj).some(function(k) { return obj[k].indexOf(search_str) !== -1 && (key = k); });
// the same with ES6 syntax:
// Object.keys(obj).some((k) => obj[k].indexOf(search_str) !== -1 && (key = k));
console.log(key); // "03"